Exercise 7-5 Solution Python Crash Course Chapter 7 : User Input And While Loops

 

📘 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:

  1. 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).

  2. 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 variable age.

  3. 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:


🔗 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

Previous Post Next Post

Contact Form