+ 1

Assert related question

How can I be sure that an user input is an integer, not a letter?

9th Dec 2019, 3:19 PM
Vagner dos Santos
Vagner dos Santos - avatar
5 Antworten
+ 4
You can test the input (let's call it inp) if it consists only of digits. inp.isdigit() It returns either True or False.
9th Dec 2019, 3:51 PM
HonFu
HonFu - avatar
+ 3
# Using try/except/else (recommended) a = input() try: int(a) except ValueError: # your code print('Not an integer!') else: # your code print('Integer') # Using assert a = input() assert a.isdigit(), 'Not a digit!'
9th Dec 2019, 5:10 PM
Asman-H
Asman-H - avatar
+ 2
You should not use assert for this, because it's only a debugging tool. Depending on how the program is run, assert statements may be ignored by the interpreter. Bad, if your code relies on them!
11th Dec 2019, 11:32 AM
HonFu
HonFu - avatar
+ 2
Agree with HonFu. Use try/else statements to handle errors
11th Dec 2019, 1:18 PM
Asman-H
Asman-H - avatar
+ 1
Thanks Asman-H and HonFu for your answers, they were very clarifying. As I didn't know there is a method for this, I was writing something like eggs = input("Enter an integer:\n") assert eggs < "a", "Not an integer" But your versions are far more advantageous.
11th Dec 2019, 11:23 AM
Vagner dos Santos
Vagner dos Santos - avatar