+ 2

Asserting inputs in py

How can we assert an input type as int ? And also if its not how can we try to get another input ?

12th Jun 2019, 8:09 AM
Amir Motamedi
Amir Motamedi - avatar
5 Answers
+ 6
while True: try: s = input() assert s.isnumeric() break except AssertionError: print('enter a number')
12th Jun 2019, 8:23 AM
Anna - avatar
+ 3
while True: try: inp = int(input()) break except: continue
12th Jun 2019, 4:52 PM
mana khorsand
mana khorsand - avatar
+ 2
Anna 's code doesn't work for negative integers, this combines the same idea, but also works for negative integers: while True: try: print("Enter any integer, please.") put = input(": ") int(put) except ValueError: print("Invalid input!") continue else: break
12th Jun 2019, 8:41 AM
Seb TheS
Seb TheS - avatar
Seb TheS you can also just do this put = int(input(": "))
12th Jun 2019, 11:55 AM
Cat Sauce
Cat Sauce - avatar
If you want to collect input = input() *Attach to variable or var If you want to collect only numbers = int(input()) *Attach to variable or vr
1st Jun 2022, 8:12 AM
Hrithika Reddy
Hrithika Reddy - avatar