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...

Python LAB 2.5.1.3 Four simple programs

 Solution for the Empty Line

empty lines in python
empty lines in python

If you have reached practice 2.5.1.3 Four simple programs, you will notice a challenge in the bottom of the exercise:

The code has one important weakness - it displays a bogus result when the user enters an empty line. Can you fix it?

Let's see how to fix it.

The problem:

User may enter an empty line or just press Enter without any data.

Solution:

  • In case user entered an empty line = a loop + else
  • We need to keep prompting user to enter data = input()

line = input("Enter a line of numbers - separate them with spaces: ")
strings = line.split()
total = 0

while strings == []: # If line is empty, string.split() will equal []
    line = input("No data found\nEnter a line of numbers - separate them with spaces: ")
    strings = line.split()
else:
   
    try:
        for substr in strings:
            total += float(substr)
        print("The total is:", total)
    except:
        print(substr, "is not a number.")


Please comment if you have other solutions 👌

Comments