Python用户输入

时间:2016-05-30 20:08:19

标签: python python-3.x

我正在编写一个提示用户输入行数的游戏。我遇到的问题是如何让程序在输入整数之前一直提示用户。如果用户输入字母或浮点数(如2.5),则int值将不起作用,因此我无法摆脱循环。程序崩溃了。 int是必不可少的,以便我可以检查数字。输入必须是偶数,它必须大于或等于4且小于等于16.谢谢!

def row_getter()->int:

    while True: 
        rows=int(input('Please specify the number of rows:'))
        if (rows%2 == 0 and  rows>=4 and  rows<=16):
            return rows
            break 

3 个答案:

答案 0 :(得分:2)

您在正确的路径上,但是您想使用HttpURLConnection / try块来尝试将输入转换为整数。如果失败(或输入不在给定范围内),你想继续并继续要求输入。

except

答案 1 :(得分:0)

我想这样做的pythonic方法是:

while True:
    try:
        rows = int(input('Please specify the number of rows:'))
    except ValueError:
        print("Oops! Not an int...")
        continue
    # now if you got here, rows is a proper int and can be used

这个成语被称为更容易请求宽恕而不是许可(EAFP)。

答案 2 :(得分:0)

还可以使isint辅助函数重用,以避免代码的主要部分中的try / except:

def isint(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def row_getter()->int:  

    while True:
        s = input('Please specify the number of rows:')
        if isint(s):
            rows = int(s)
            if (rows % 2 == 0 and rows >= 4 and rows <= 16):
                return rows