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

 

πŸ“˜ 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:

  1. Initialize a counter variable:

    The variable total_toppings is initialized to 0. This variable keeps track of the total number of toppings added and acts as an active variable to control the loop's duration.

  2. Set a conditional test in the while loop:

    The while loop runs as long as total_toppings is less than 5. This condition ensures that the loop stops automatically after five toppings have been added.

  3. Check for the quit condition:

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

  4. Handle valid toppings:

    If the user enters a valid topping (anything other than 'quit'), the program acknowledges the topping and increments the total_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:


πŸ”— 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

“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