-1

I am new with "try" and "except" keyword in Python, today I learned it and tried to write a program that allows users to enter an integer, if they did not enter an integer, they will enter again. My idea is I will use the while loop with "try" and "except", but it seems like the while loop is not working in the situation.

error = False
while error == False: 
    try:
        number = int(input("Enter a number: "))
        error = True
    except:
        error = False

Is there anything that I missed? Thank you guys

Thanh Toan
  • 11
  • 3
  • 3
    "it didn't work" doesn't give us much to go on. Was there an error message? Can you give us a more specific description of what happened? – user2357112 Aug 18 '20 at 08:33
  • It should be other way around. `error = True` should be in `except:` block. – Gram Aug 18 '20 at 08:37
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Aug 18 '20 at 08:39
  • @Gram: Due to the way the loop test is written, that change would result in the loop ending once an invalid input is made, instead of ending upon a valid input. – user2357112 Aug 18 '20 at 08:39

1 Answers1

2

More elegant way of doing this would be

while True:
    try:
        number = int(input("Enter number: "))
        break
    except ValueError:
        pass
vahvero
  • 525
  • 11
  • 24