我尝试创建一个要求3-8之间的整数的函数,并将继续询问,直到用户输入3-8之间的整数。所以它会再次询问你输入0,-1,9或者#34;兔子"。
到目前为止,我有这个:
def GetNumberOfColours():
NumberOfColours = None
while type(NumberOfColours) != int or int(NumberOfColours) < 3 or int(NumberOfColours) > 8:
print "Please enter the amount of colours you would like to play with (min 3, max 8)."
NumberOfColours = raw_input()
NumberOfColours = int(NumberOfColours)
但是这个代码目前还没有工作,因为它需要原始输入,如果是这样的话,就不会将其视为整数。但是如果我使用input()那么它就不会接受一个可以输入并停止代码的字符串。 我怎样才能做到这一点?
答案 0 :(得分:2)
type(NumberOfColours)
将始终为str
(或在第一次运行时为NoneType
),因为raw_input()
会返回一个字符串。
你应该这样做:
def get_number_of_colours():
while True:
print "Please enter the amount of colours you would like to play with (min 3, max 8):",
try:
num_colours = int(raw_input())
except ValueError: # gets thrown on any input except an integer value
continue
if 3 <= num_colours <= 8:
return num_colours
答案 1 :(得分:1)
您需要缩进最后一行,让脚本重复将输入转换为整数。
然后你会发现输入“兔子”会产生ValueError
因为int()
无法将其转换为数字。这可以使用try/except
:
def GetNumberOfColours():
NumberOfColours = None
while type(NumberOfColours) != int or int(NumberOfColours) < 3 or int(NumberOfColours) > 8:
print "Please enter the amount of colours you would like to play with (min 3, max 8)."
NumberOfColours = raw_input()
try:
NumberOfColours = int(NumberOfColours)
except ValueError:
NumberOfColours = None
答案 2 :(得分:1)
将此项用于您的生产线:
while !NumberOfColors.isDigit() or int(NumberOfColours) < 3 or int(NumberOfColours) > 8: