Exercise 7
Write a Python algorithm that asks the user to enter 3 numbers x, y, and z and display their maximum without using the max() function.
Solution
# Ask the user to enter three numbers x = float(input("Enter the first number: ")) y = float(input("Enter the second number: ")) z = float(input("Enter the third number: ")) # Find the maximum of the three numbers without using the max() function max_num = x if y > max_num: max_num = y if z > max_num: max_num = z # Display the maximum number print("The maximum of the three numbers is", max_num) """ output: Enter the first number: 3.75 Enter the second number: 7.2 Enter the third number: 3.0 The maximum of the three numbers is 7.2 """
In this program:
- we initialize max_num: to be the first number x.
- We then use a series of if statements: to check whether y or z are larger than max_num.
- If y is larger than max_num: we update max_num to be y.
- Similarly, if z is larger than max_num: we update max_num to be z.
- By the end of the if statements: max_num will hold the largest of the three numbers. Finally, we print out the value of max_num.
Younes Derfoufi
my-courses.net
[…] Exercise 7 || Solution […]