π 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:
-
Start an infinite loop:
The
while True
statement creates an infinite loop that will continue running until explicitly broken using thebreak
statement. -
Prompt for a pizza topping:
The user is asked to enter a pizza topping. The input is stored in the variable
topping
. -
Check for the quit condition:
An
if
statement checks whether the user entered'quit'
. Thelower()
method is used to make the comparison case-insensitive. If the user enters'quit'
, thebreak
statement is executed, which exits the loop. -
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:
- ➤ 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