1

I am very new to programming and tried to make a age checker code, however the loop to make sure user input is a number does not work.

If a string is entered, for example hello, the input passes the .isdigit() condition, and messes up the last if statement.

Any help would or advice on how to construct the number checker loop properly, so that strings are not entered into the last if statement would be greatly appreciated. Here is my code:

while True:
    age = input('Enter age:    ')
    if  age.isdigit():
        print('Thank you, number entered is:', age)
    else:
        print('A number must be entered')
        break
print('Please enter age')        
used_variable = age
if used_variable >  18:
    print('user is older than 18') 
Avishay Cohen
  • 1,978
  • 2
  • 21
  • 34
Jacob
  • 19
  • 1
  • 1
    Once you know that it only consists of digits you still have to cast your string into an integer with the function int() – leoburgy Nov 21 '18 at 13:19
  • are you using python3 or python2 ? like @Adelin mentiond below, [they have different output](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers) depending on the python version so `isdigit()` might not be a good fit here. also – Avishay Cohen Nov 21 '18 at 14:29

1 Answers1

0

You were breaking out of loop when user inserted incorrect value (not digit) instead of letting loop go on to ask him again, you should have break the loop when user typed correct value.

while True:
    age = input('Enter age:    ')
    if  age.isdigit():
        print('Thank you, number entered is:', age)
        break
    else:
        print('A number must be entered')

#print('Please enter age')
used_variable = int(age)
if used_variable >  18:
    print('user is older than 18') 
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
  • 1
    so, for an 'int' that does a conversion, you copy pasted an answer, with no explanation whatsoever, an answer that was already given countless of times? Yeah, thats a -1 – Adelin Nov 21 '18 at 13:14
  • I did not copy pasted any answer, and I think its ok to first post code to let author see and create explanation in meantime. – Filip Młynarski Nov 21 '18 at 13:15
  • If you think this answer is a good answer that was not [already posted before](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers), then keep it, but I stick with my downvote – Adelin Nov 21 '18 at 13:29
  • If author's code only problem would be about converting input to integer you would be right, but there's other bugs that I shown and explained. – Filip Młynarski Nov 21 '18 at 13:32
  • Glad to have been of help! Feel free [to accept one of the answers](https://meta.stackexchange.com/a/5235) if you feel it was useful to you. :) You can only pick one, the choice is yours. The idea is that you pick the one you feel helped you the most. There is no requirement that you select any, not accepting an answer is also allowed. – Filip Młynarski Nov 22 '18 at 12:17