我正在开发一个简单的转换程序,但我遇到了阻止用户键入需要整数的字符串的问题:
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")当涉及到inputcheck时,if语句的else部分无法工作,我不知道原因。请帮帮忙。
发布于 2014-02-07 04:36:11
while True:
try:
choice = int(input('please choose type of convert'))
except ValueError:
# user entered an input that couldn't be converted to int
continue
else:
if not 1 <= choice <= 3:
# valid int, invalid choice
continue
# success. stop looping
break现在,您有了一个表示它们的输入的int。它将继续询问,直到他们成功输入int
发布于 2014-02-07 05:03:09
这将保持程序循环,直到用户选择退出。我使用了一个浮点数作为第二个用户输入,因为用户可能需要找到2.5英寸或类似的值。
while True:
try:
choice = int(input("""please choose type of convert:
1. Centimeters to inches
2. Inches to centimeters
3. Exit"""))
if choice == 1:
while True:
try:
cm = float(input ("Please type in value in centimeters."))
cmsum = cm * 0.39 # multiplies user input by 0.39
print (cm, " centimeters is ", cmsum, " inches")
break
except ValueError:
print('error')
elif choice ==2:
while True:
try:
stuff()
break
except ValueError:
print('error')
elif choice == 3:
print('Thanks!')
break
except ValueError:
print('error')https://stackoverflow.com/questions/21613455
复制相似问题