Write a function called largest3 which takes 3 numbers as parameters and returns the largest of the 3. Write a program which takes 3 numbers as input from the user and then calls the function with those 3 numbers as parameters. The function will reutrn the largest number. Your program should then output this returned largest number. The input and output parts should be outside the function. The functions should only take 3 numbers as parameters and return the largest one.

Respuesta :

Answer:

The solution code is written in Python.

  1. def largest3(num1, num2, num3):
  2.    largest = num1
  3.    if(largest < num2):
  4.        largest = num2
  5.    
  6.    if(largest < num3):
  7.        largest = num3
  8.    
  9.    return largest
  10. first_num = int(input("Enter first number: "))
  11. second_num = int(input("Enter second number: "))
  12. third_num = int(input("Enter third number: "))
  13. largest_number = largest3(first_num, second_num, third_num)
  14. print("The largest number is " + str(largest_number))

Explanation:

Create function largest3

  • Firstly, we can create a function largest3 which take 3 numbers (num1, num2, num3) as input. (Line 1).
  • Please note Python uses keyword def to denote a function. The code from Line 2 - 10 are function body of largest3.
  • Within the function body, create a variable, largest, to store the largest number. In the first beginning, just tentatively assign num1 to largest. (Line 2)
  • Next, proceed to check if the current "largest" value smaller than the num2 (Line 4). If so, replace the original value of largest variable with num2 (Line 5).
  • Repeat the similar comparison procedure to num3 (Line 7-8)
  • At the end, return the final value of "largest" as output

Get User Input

  • Prompt use input for three numbers (Line 13 -15) using Python built-in input function.
  • Please note the input parts of codes is done outside of the function largest3.

Call function to get largest number and display

  • We can simply call the function largest by writing the function name largest and passing the three user input into the parenthesis as arguments. (Line 17)
  • The function largest will operate on the three arguments and return the output to the variable largest_number.
  • Lastly, print the output using Python built-in print function. (Line 18)
  • Please note the output parts of codes is also done outside of the function largest3.