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

Popular posts from this blog

فرصتك للدراسة في ألمانيا: منحة ممولة بالكامل لطلاب الدراسات العليا

How to Deactivate Screen Reader in Kali Linux

Murphy's Law: Expect the Unexpected

Python 3.2.1.14 LAB: Essentials of the while loop

7 Reasons Why You Need to Learn English

Data Analysis Roadmap 2026: From Excel Lover to Python-Powered Analyst

15 Python Builtin-Functions You Need to Master as a Beginner

Prefixes vs Suffixes ? What are they?

Python 4.3.1.7 LAB: How many days: writing and using your own functions

Python 4.3.1.6 LAB: A leap year: writing your own functions