2

我正在尝试创建一个请求 3-8 之间的整数的函数,并将继续询问直到用户输入 3-8 之间的整数。所以它会再次询问您是否输入 0、-1、9 或“兔子”。

到目前为止,我有这个:

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() 那么它不会接受可以输入的字符串并停止代码。我怎样才能使这项工作?

4

3 回答 3

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
于 2013-11-07T12:22:41.357 回答
1

您需要缩进最后一行以使脚本反复将输入转换为整数。

然后你会发现输入“rabbits”会产生一个ValueErroras int()can't convert that to a number。这可以通过以下方式处理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
于 2013-11-07T12:22:45.543 回答
1

将此用于您的 while 行:

while !NumberOfColors.isDigit() or int(NumberOfColours) < 3 or int(NumberOfColours) > 8:
于 2013-11-07T12:24:40.303 回答