π Python Crash Course – Chapter 7: User Input And while loops – Exercise 7-6 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 7-6
Task:
Write different versions of either Exercise 7-4 or Exercise 7-5
that do each of the following at least once:
• Use a conditional test in the while statement to stop the loop .
• Use an active variable to control how long the loop runs .
• Use a break statement to exit the loop when the user enters a 'quit' value
✅ Solution Code:
# exercise 7-4
# Pizza Toppings
total_toppings = 0 #total number of toppings
while total_toppings < 5: #conditional test in the while statement to stop the loop
topping = input("Enter a pizza topping (or 'quit' to finish): ")
if topping.lower() == 'quit': #break the loop
break
else:
print(f"Adding {topping} to your pizza.")
total_toppings += 1 #increment the number of toppings
π§ Code Explanation:
-
Initialize a counter variable:
The variable
total_toppings
is initialized to0
. This variable keeps track of the total number of toppings added and acts as an active variable to control the loop's duration. -
Set a conditional test in the
while
loop:The
while
loop runs as long astotal_toppings
is less than5
. This condition ensures that the loop stops automatically after five toppings have been added. -
Check for the quit condition:
An
if
statement checks whether the user entered'quit'
. Thelower()
method ensures the comparison is case-insensitive. If the user enters'quit'
, thebreak
statement is executed, which immediately exits the loop. -
Handle valid toppings:
If the user enters a valid topping (anything other than
'quit'
), the program acknowledges the topping and increments thetotal_toppings
counter by 1. This ensures the loop progresses toward its stopping condition.
π Output:
Enter a pizza topping (or 'quit' to finish): wheat
Adding wheat to your pizza.
Enter a pizza topping (or 'quit' to finish): cabbage
Adding cabbage to your pizza.
Enter a pizza topping (or 'quit' to finish): papaya
Adding papaya 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