Featured Posts

CS50 Python , Nutrition Facts Table

Image
Nutrition Facts: Python Practice for Beginners Nutrition Facts Table for Python Practice Welcome to this comprehensive guide for Python beginners! If you are learning how to work with lists, dictionaries, and loops, this post will help you build practical skills using a real-world example: nutrition facts for fruits. Understanding how to organize and manipulate data is a key part of programming, and this exercise will give you hands-on experience. Below is a sample table of fruits and their calorie values, formatted as a Python list of dictionaries. This structure is ideal for coding exercises, projects, or even building your own nutrition calculator. You can expand this list, add new fruits, or use it as a foundation for more advanced Python tasks. Python List of Dictionaries Example: fruits = [ {'name': 'Apple', 'calories': 130}, {'name': 'Avocado', 'calories': 50}, {'name': 'Banana', 'ca...

Python3.2.1.9 LAB: The break statement - Stuck in a loop

 3.2.1.9 LAB: The break statement - 

Stuck in a loop

The break statement - Stuck in a loop
The break statement - Stuck in a loop

If you're taking PCAP - Programming Essentials In Python , you may have encountered this question in 3.2.1.9 LAB: The break statement - Stuck in a loop.

Scenario

The break statement is used to exit/terminate a loop.

Design a program that uses a while loop and continuously asks the user to enter a word unless the user enters "chupacabra" as the secret exit word, in which case the message "You've successfully left the loop." should be printed to the screen, and the loop should terminate.

Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.

2 Solutions

First Solution (with break)

As the exercise asks, you need to include the keyword (break)

secret_word = ""
while True:
    secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")
    if secret_word == "chupacabra":
        print("You've successfully left the loop.")
        break

Second Solution (without break, but with else)

secret_word = "chupacabra"
word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")

while word != secret_word:
    word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop: ")
else:
    print("You've successfully left the loop.")


 =================================================================================

Follow the blog to be the first to know ❤

Comments