-->

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 👌

Post a Comment

0 Comments