我正在开发一个简单的转换程序,但是我一直在阻止用户输入一个需要整数的字符串:
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
,else
语句的if
部分不起作用,我不知道为什么会这样。请帮忙。
答案 0 :(得分:2)
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
答案 1 :(得分:0)
这将使程序循环,直到用户选择退出。我使用浮动作为第二个用户输入,因为用户可能需要找到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')