Checking variable type in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Checking variable type in Python

I am making a dice roller and came across a possible hindrance: while submiting how many dices or how many sides the dice has, I convert the input to an integer; in the case I accidentaly write a string in the input section, the code returns an error and stops. How can I bypass this error message and display my own error message without stoping the code? (I was thinking on checking the var type, but so far I can't recall any way of doing that)

20th May 2019, 11:22 PM
dino460
dino460 - avatar
3 Answers
+ 4
try: n = int(input()) except: print("Please enter only integers")
20th May 2019, 11:24 PM
Diego
Diego - avatar
+ 4
if isinstance(var, int): # the variable is an integer # proceed normally else: # it isn't an integer # show error message
20th May 2019, 11:34 PM
Eduardo Petry
Eduardo Petry - avatar
+ 1
alternative, n = input() if not n.isdigit(): print(“error”) else: n = int(n)
21st May 2019, 3:01 AM
Choe
Choe - avatar