简体   繁体   English

如何只接受3-8之间的整数而不接受字符串? (Python 2.7.5)

[英]How to only accept integer between 3-8 and not strings? (Python 2.7.5)

I'm trying to make a function that asks for an integer between 3-8 and will continue asking until the user inputs an integer between 3-8. 我正在尝试制作一个函数,要求3-8之间的整数,并将继续询问直到用户输入3-8之间的整数。 So it will ask again if you enter 0, -1, 9 or "rabbits". 因此,它将再次询问您是否输入0,-1、9或“兔子”。

So far I have this: 到目前为止,我有这个:

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)

But this code at the moment won't work as it takes the raw input and won't see it as an integer if it is. 但是此代码目前无法正常工作,因为它需要原始输入,并且不会将其视为整数。 But if I use input() then it won't accept a string which could be input and stop the code. 但是,如果我使用input(),它将不会接受可以输入的字符串并停止代码。 How can I make this work? 我该如何进行这项工作?

type(NumberOfColours) will always be str (or NoneType in the very first run) because raw_input() returns a string. 因为raw_input()返回一个字符串,所以type(NumberOfColours)将始终为str (或在第一次运行时为NoneType raw_input()

You should be doing it like this: 您应该这样做:

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

You need to indent the last line to have the script repeatedly convert the input to an integer. 您需要缩进最后一行,以使脚本重复将输入转换为整数。

You'll then discover that entering "rabbits" will produce a ValueError as int() can't convert that to a number. 然后,您会发现输入“兔子”将产生ValueError因为int()无法将其转换为数字。 This can be handled with a try/except : 可以通过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

将此用于您的while行:

while !NumberOfColors.isDigit() or int(NumberOfColours) < 3 or int(NumberOfColours) > 8:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM