-1

I wanna do this but i got 3 issues a s I commented:

age = input("How old are you ? ")
if type(age) != int: # this line does't work
    restart = input("invalid input. Do you want to restart ? [y/n]")
    if restart == "y" :
        #restart the program
    else :
        #exit the program
  • 1
    `input` returns a `str`, even if that string happens to represent a number. – Brian Mar 18 '21 at 14:53
  • so u say i shouldnt use input in the first place to get age? what should i do then? – Reza Rezaee zadeh Mar 18 '21 at 15:01
  • 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) – Gino Mempin Mar 20 '21 at 02:59

1 Answers1

1

Use a try-except block to check the conversion of the input (str) to int

age = input("How old are you ? ")
try:
    age = int(age)
except ValueError:
    restart = input("invalid input. Do you want to restart ? [y/n]")
    if restart == "y" :
        #restart the program
    else :
        #exit the program
frab
  • 1,045
  • 1
  • 3
  • 13
  • 2
    You may want to read [What is wrong with using a bare 'except'?](https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except) – Brian Mar 18 '21 at 15:02
  • @Brian you're right, I edited the post, thanks. – frab Mar 18 '21 at 15:03