0

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?

1
  • 2
    Yes there is a better way, but if you are as much of a beginner as you say you are, good job on thinking it through and doing something that made sense in your head to get it to work Commented Oct 5, 2017 at 5:33

3 Answers 3

3

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")
Sign up to request clarification or add additional context in comments.

3 Comments

i think OP asks for keeping the loop running if the answer is not valid
@PRMoureu, yes, my mistake. But it has no sense
it's just to make the user input a valid number
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.

3 Comments

(the last continue is not needed if there is no code after)
The continue makes it loop, not continue to the end
Otherwise it would keep going once they gave an integer
0
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.