簡體   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