【问题标题】:How do I limit my users input to a single digit? (Python)如何将我的用户输入限制为单个数字? (Python)
【发布时间】:2016-09-26 13:46:00
【问题描述】:

如果输入了 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')

【问题讨论】:

  • 如果数字 >9 或数字
  • 或者,数字 =-9

标签: python


【解决方案1】:

使用 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)

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

【讨论】:

  • input() 在 python 2 中安全吗?从我读到它类似于eval(raw_input())
  • @Aaron:OP 似乎使用的是 Python 3。如果 OP 使用的是 Python 2,那么 OP 应该使用 raw_input 而不是 input,因为你说的原因。
  • @StevenRumbalski 我看到了,并且我知道input() 在 Python 3 中的功能类似于 raw_input()。但我很好奇 2.7 版本从不受信任的输入角度来看是否安全。 (与这个问题无关......)
  • @Aaron:在 Python 2 中,input() 不安全,不,因为它是自动的eval(raw_input())。然而,这不是 Python 2。
【解决方案2】:

根据之前的answer,还有另一种只获取一个字符的选项:

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...'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多