繁体   English   中英

如何将我的用户输入限制为一位数字? (蟒蛇)

[英]How do I limit my users input to a single digit? (Python)

我想让我的程序说出“无效输入”(如果输入的是2位或更多位数字),那么有什么方法可以将我的用户输入限制为python中的一位数字?

这是我的代码:

print('List Maker')
tryagain = ""

while 'no' not in tryagain:
    list = []

    for x in range(0,10):
        number = int(input("Enter a number: "))
        list.append(number)

    print('The sum of the list is ',sum(list))
    print('The product of the list is ',sum(list) / float(len(list)))
    print('The minimum value of the list is ',min(list))
    print('The maximum vlaue of the list is ',max(list))
    print(' ')
    tryagain = input('Would you like to restart? ').lower()
    if 'no' in tryagain:
        break
print('Goodbye')

使用while循环而不是for循环,当您有10位数字时中断,并拒绝接受9以上的任何数字:

numbers = []
while len(numbers) < 10:
    number = int(input("Enter a number: "))
    if not 1 <= number <= 9:
        print('Only numbers between 1 and 9 are accepted, try again')
    else:
        numbers.append(number)

请注意,我将列表重命名为numbers list是内置类型,您通常希望避免使用内置名称。

根据先前的答案 ,还有一种选择只获取一个字符:

import termios
    import sys, tty
    def getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


numbers = []
while len(numbers) < 10:
    try:
        ch = int(getch())
    except:
        print 'error...'

暂无
暂无

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

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