I'm developing a simple conversion program, but I got stuck on preventing the user from typing in a string where integers are expected:
choicecheck = 1
inputcheck = 1
while choicecheck == 1:
choice = input ("""please choose type of convert:
1. Centimeters to inches
2. Inches to centimeters
3. Exit""")
while inputcheck == 1:
if choice == "1":
cm = int(input ("Please type in value in centimeters."))
if type(cm) == int:
cmsum = cm * 0.39 # multiplies user input by 0.39
print (cm, " centimeters is ", cmsum, " inches")
choicecheck = 0
inputcheck = 0
else:
print("Sorry, invalid input")
When it comes to inputcheck, the else part of the if statement does not work, and I have no idea why is that. Please help.
type(cm)can only ever beintbecausecmwas constructed using a call toint()on the user's input. But that call fails if the user happens to enter something that can't be interpreted as an integer. For this, you use atry/exceptstatement like the one @mhlester proposes. Type checking is rarely ever done in Python.