我遇到了一些麻烦,我已完成程序的这一部分,它按计划运行,它存储变量并成功检查所有验证,但我需要它进行验证,以便只能输入数字。只要按下字母键,程序就会崩溃。
我知道我需要在某个地方使用selection.isdigit,我已经在几个不同的地方尝试过了,但是当我把它放在看起来正确的地方时,程序会崩溃,因为isdigit只适用于字符串,并给出程序中的数字验证,程序在尝试使用字符串时崩溃。有人可以帮助我吗?
while True:
if amountwanted > 0:
selection = int(input("What flavour pizza would you like? (1-12): "))
if selection < 1 or selection > 12:
print("You must enter a pizza between 1 and 12")
print("")
else:
if selection <= 7:
orderedstandardpizzas.append(selection)
else:
orderedgourmetpizzas.append(selection)
amountwanted = amountwanted - 1
else:
break
答案 0 :(得分:1)
您对int()
的使用会引发错误,因为它只接受可以被解释为数字的字符串。
您可以捕获异常而不是检查输入中的每个字符:
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "You must enter a number!"
break
上面的代码段会替换旧的selection = ...
行,该行已缩进4个空格以匹配我插入的新try
/ except
块。完整的代码最终如下:
while True:
if amountwanted > 0:
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "You must enter a number!"
break
if selection < 1 or selection > 12:
print("You must enter a pizza between 1 and 12")
print("")
else:
if selection <= 7:
orderedstandardpizzas.append(selection)
else:
orderedgourmetpizzas.append(selection)
amountwanted = amountwanted - 1
else:
break
答案 1 :(得分:0)
试试这个:
selection = raw_input("What flavour pizza would you like? (1-12): ");
if (selection.isdigit())
numSelection = int(selection);
if (numSelection < 1 or numSelection > 12:
// carry on
else:
// else case
else:
//print error message. Break out of loop here if required.
答案 2 :(得分:0)
考虑一下
行 selection = int(input("What flavour pizza would you like? (1-12): "))
input(...)
函数根据用户的输入返回一个字符串;然后通过int(...)
将其转换为整数。 [正如其他人所指出的那样,3.x中的input
相当于2.x上的raw_input
。]
所以你基本上有两个选择。首先,您可以将非数字输入视为可以捕获的实际错误,并在发生错误时使用continue
返回循环的开头:< / p>
try:
selection = int(input("What flavour pizza would you like? (1-12): "))
except ValueError:
print "Error message"
continue
这可能是最合适的pythonic策略。
相反,您可以检查输入确实是由数字组成的,虽然它比这更复杂,因为当前版本允许前后空格,所以你可以做类似的事情
string_selection = input("What flavour pizza would you like? (1-12): ")
if not string_selection.strip().isdigit():
continue
selection = int(string_selection)
但这更复杂!