我希望我的程序能说“输入无效”。如果输入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')
答案 0 :(得分: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
是内置类型,您通常希望避免使用内置名称。
答案 1 :(得分: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...'