Home > Blockchain >  How to break loop when int input is empty/blank?
How to break loop when int input is empty/blank?

Time:09-19

I want the loop to break when user inputs empty/blank and cant figure it out. Just gives me value error.

a = 0
x = 0
while True:
    num1 = int(input("Give number: "))
    if num1 == "":
        break
    x  = num1
    a  = 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)

CodePudding user response:

You can try this try-except:

a = 0
x = 0
while True:
    try: 
        num1 = int(input("Give number: "))
    except ValueError as err:
        print("Empty `number`")
        break
    x  = num1
    a  = 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)

Output:

Give number: 2
Give number: 3
Give number: 
Empty `number`
Numbers Given:  2
Sum of numbers:  5

CodePudding user response:

a = 0
x = 0
while True:
    num1 = input("Give number: ")
    if num1 == "":
        break
    x  = int(num1)
    a  = 1
print("Numbers Given: ", a)
print("Sum of numbers: ",x)
  • Related