nh3
nh3

Reputation: 55

Better way to ask user input in integer form in Python?

So I'm kind of very beginner to programming and just learning yet the basics. Now I would like to have my python program to ask the user to give a number and keep asking with a loop if string or something else is given instead.

So this is the best I came out with:

value = False
while value == False:
    a = input("Give a number: ")
    b = 0
    c = b
    try:
        int(a)
    except ValueError:
        print("No way")
        b += 1
    if c == b:
        value = True

So is there easier and better way to do this?

Upvotes: 0

Views: 80

Answers (3)

Jacob John
Jacob John

Reputation: 1

while True:
    try:
        a = int(input("Give a number: "))
        break
    except ValueError:
        print("No way")
        continue

This will continue to prompt the user for an integer till they give one.

Upvotes: 1

amarynets
amarynets

Reputation: 1815

You can use this:

while True:
    try:
        a = int(input("Give a number: "))
        break
    except ValueError:
        print("No way")

or this:

while True:
    a = input("Give a number: ")
    if a.isdigit():
        break
    print("No way")

Upvotes: 3

Sudeep Padalkar
Sudeep Padalkar

Reputation: 83

value = True
while value == True:
     a = input("Give a number: ")
     try:
        int(a)
     except ValueError:
        print("No way")
        continue
     print("Yay a Number:", a)
     value = False

Is this what you need?

Upvotes: 0

Related Questions