2016-09-26 121 views
1

如果输入2位或更多位数,我希望我的程序说'无效输入',那么有没有办法将我的用户输入限制在python中的单个数字?如何限制我的用户输入为单个数字? (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') 
+1

如果数> 9或数<-9 –

+0

替代地,而数<= 9和编号> = - 9 –

回答

4

使用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是一种内置类型,您通常希望避免使用内置名称。

+0

在python 2中'input()是安全的吗?从我读过的它类似于'eval(raw_input())' – Aaron

+0

@Aaron:OP似乎在使用Python 3.如果OP使用Python 2,那么OP应该使用'raw_input'而不是'input'作为你说的原因。 –

+0

@StevenRumbalski我明白了,我明白'input()'在Python 3中的功能是'raw_input()'。但是我很好奇2.7版本是否可以从不可信的输入的角度来看是安全的。 (不涉及这个问题......) – Aaron

0

还有另一种选择用于获取只有一个字符的基础上,此以前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...'