-1

I want to ask a user for a number(among other things) and if they input anything other than an int, it should tell them to try again.

I'm still getting use to python syntax, what's the best way to do this?

excerpt below of what I tried:

try:
    num = int(i)
except ValueError:
    while type(num) != int:
        num = input("Please input an actual number or q to quit: ") 
Jake Myers
  • 13
  • 3
  • what is the purpose of the try-except? – Azsgy Mar 28 '18 at 18:59
  • 2
    Have you read through the python documentation? There are no doubt gazillions of examples there and on the internet. – Bryan Oakley Mar 28 '18 at 19:00
  • Possible duplicate of [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) – Patrick Artner Mar 28 '18 at 19:43

1 Answers1

1
while True:
    num = input("Input a number. ")
    if num.isdigit()==False:
        print("Try again.")
    else:
        break

This should work unless if there's a negative value entered in which case you need to make a check if the first character is a - sign.

Dan
  • 527
  • 4
  • 16
  • read [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) - there are several better options in it. - yours f.e. does not lead to having a number at the end, negatives have to be handled seperately as you mentioned and whitespace might throw yours off as well - also read [isdigit](https://docs.python.org/3/library/stdtypes.html#str.isdigit) - it represents digits that are not ok when you need an integer from it (edge cases) – Patrick Artner Mar 28 '18 at 19:44
  • Ah ok. This was just a solution that I used off the top of my head but I'll check that out. Thanks – Dan Mar 28 '18 at 19:53