我主要使用的是Python 3.2,但仅仅是出于可视化目的而转向2.7。我似乎无法使循环形成无限循环,例如,如果用户输入错误的短语,则在输入错误的变量后代码就会中断。
measure = raw_input("what form of measurement do you want to use:
(enter CM or IN): ")
while True:
if measure == str('cm'):
break
elif measure == str("in"):
break
else:
measure = input("please enter cm or in")
continue
答案 0 :(得分:1)
当我尝试它时,您尝试在raw_input
块中使用else
上的输入时抛出错误。试试以下内容:
measure = raw_input("what form of measurement do you want to use:
(enter CM or IN): ")
while True:
if measure == str('cm'):
break
elif measure == str("in"):
break
else:
measure = input("please enter cm or in")
continue
更好的是,为了避免使用break
或continue
,您可以使用以下内容,这会简化您的逻辑并考虑大小写:
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ").lower()
while measure != 'cm' and measure != 'in':
measure = raw_input("please enter cm or in").lower()
答案 1 :(得分:0)
以下代码是已经过测试的评论中代码的混搭
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ")
while True:
if measure == 'cm':
break
elif measure == "in":
break
else:
measure = raw_input("please enter cm or in: ")
continue
答案 2 :(得分:0)
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ")
b = True
while b:
if measure == 'cm' or measure == "in":
b = False
else:
measure = raw_input("please enter cm or in ")
只需将您的上一个input
更改为raw_input
答案 3 :(得分:0)
缩进怎么样?不要忘记缩进是python知道的方式,如果你仍然在while / if / for / ...语句中。
我没有在这里有一个python翻译,但我的猜测是,如果你正确缩进它应该有效。此外,使用while measure != "cm" and measure != "in"
measure = raw_input("blablabla")
while measure != "cm" and measure != "in":
measure = raw_input("please enter cm or in: ")
答案 4 :(得分:0)
您可以重新编写代码,以便只有一个数据提示。删除不需要的str
次转化,使用大写字母进行测试,然后检查输入的值是否在所需值列表中。 (并通过将字符串放在多行上来摆脱那种语法错误)
while True:
measure = raw_input("what form of measurement do you want to use:"
" (enter CM or IN): ").strip()
if measure.upper() in ("CM", "IN"):
break
print("Incorrect input, try again")