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

 

📘 Python Crash Course – Chapter 7: User Input And while loops – Exercise 7-4 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 7-4

Task:
Write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value . As they enter each topping, print a message saying you’ll add that topping to their pizza

✅ Solution Code:



while True:
    topping = input("Enter a pizza topping (or 'quit' to finish): ")
    if topping.lower() == 'quit':
        break
    else:
        print(f"Adding {topping} to your pizza.")

🧠 Code Explanation:

  1. Start an infinite loop:

    The while True statement creates an infinite loop that will continue running until explicitly broken using the break statement.

  2. Prompt for a pizza topping:

    The user is asked to enter a pizza topping. The input is stored in the variable topping.

  3. Check for the quit condition:

    An if statement checks whether the user entered 'quit'. The lower() method is used to make the comparison case-insensitive. If the user enters 'quit', the break statement is executed, which exits the loop.

  4. Handle other inputs:

    If the user enters anything other than 'quit', the program acknowledges the topping and continues the loop, allowing the user to enter more toppings.

🔍 Output:


Enter a pizza topping (or 'quit' to finish): cream
Adding cream to your pizza.
Enter a pizza topping (or 'quit' to finish): corn
Adding corn to your pizza.
Enter a pizza topping (or 'quit' to finish): quit

📚 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