π Python Crash Course – Chapter 7: User Input And while loops – Exercise 7-5 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 7-5
Task:
A movie theater charges different ticket prices depending on
a person’s age . If a person is under the age of 3, the ticket is free; if they are
between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is
$15 . Write a loop in which you ask users their age, and then tell them the cost
of their movie ticket
✅ Solution Code:
while True:
age = int(input("Enter your age: "))
if age < 3:
print("Your ticket is free!")
elif 3 <= age <= 12:
print("Your ticket is $10.")
elif age > 12:
print("Your ticket is $15.")
else:
print("Invalid age entered.")
π§ Code Explanation:
-
Start an infinite loop:
The
while True
statement creates an infinite loop that will continue running until explicitly stopped (e.g., by breaking the loop). -
Prompt for age:
The user is asked to enter their age. The input is converted to an integer using the
int()
function and stored in the variableage
. -
Check ticket pricing conditions:
The program uses an
if-elif-else
chain to determine the ticket price based on the user's age:if age < 3
: If the age is less than 3, the ticket is free.elif 3 <= age <= 12
: If the age is between 3 and 12 (inclusive), the ticket costs $10.elif age > 12
: If the age is greater than 12, the ticket costs $15.else
: If the input does not match any of the above conditions, an error message is displayed indicating an invalid age.
π Output:
Enter your age: 5
Your ticket is $10.
Enter your age: 1
Your ticket is free!
Enter your age: 25
Your ticket is $15.
Enter your age: 100
Your ticket is $15.
Enter your age: 50
Your ticket is $15.
π Related Exercises from Chapter 7:
- ➤ Exercise 7-1 | Rental Car
- ➤ Exercise 7-2 | Restaurant Seating
- ➤ Exercise 7-3 | Multiples of Ten
- ➤ Exercise 7-4 | Pizza Toppings
- ➤ Exercise 7-5 | Movie Tickets
- ➤ Exercise 7-6 | Three Exits
- ➤ Exercise 7-7 | Infinity
- ➤ Exercise 7-8 | Deli
- ➤ Exercise 7-9 | No Pastrami
- ➤ Exercise 7-10 | Dream Vacation
π Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”
— Only Python
π Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips
πTrending Topics
π Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment