Exercise 6
Write a Python algorithm that asks the user to enter their age and display the message "You're Major!" If the age typed is greater than or equal to 18 and the message "you are under age!" If the typed age is less than 18.
Solution
# ask the user to enter their age age = int(input("Please enter your age: ")) if age >= 18: print("You're Major!") else: print("You are under age!"
In this program:
- The program first prompts: the user to enter their age using the input() function. The input is converted to an integer using the int() function and stored in the age variable.
- if statement: to check if the age is greater than or equal to 18.
- If age is greater than 18: the program displays the message "You're Major!" using the print() function.
- If the age is less than 18: the program displays the message "You are under age!" using the print() function.
- Note that the if statement uses the comparison operator >=: to check if the age is greater than or equal to 18. If the age was a string instead of an integer, the program would not work correctly, so it is important to convert the input to an integer using the int() function.
Younes Derfoufi
my-courses.net
[…] Exercise 6 || Solution […]