迭代并打印出错信息
问题描述:
对于python Bootcamp,我正在研究一个程序,它反复要求输入“名称”并将其打印出来。迭代并打印出错信息
当用户输入“bob”时,程序必须打印出“哦,不是你,bob!”,并打印出以前输入的最短和最长的名字。
如果用户输入除字符串以外的任何内容(例如数字),程序必须打印出错误消息并继续再次询问名称。
我不知道如何当用户输入一个int,一个float,还是其他什么东西不是像“罗密欧”的字符串打印出错误消息
请参阅我下面的程序:
`new_name = ''
while new_name != 'bob':
#Ask the user for a name.
new_name = input("Please tell me someone I should know, or enter 'quit': ")
print('hey', new_name, 'good to see you')
if new_name != 'bob':
names.append(new_name)
largest = None
for name in names:
if largest is None or len(name) > len(largest) :
largest = name
smallest = None
for name in names:
if smallest is None or len(name) < len(smallest) :
smallest = name
print ('oh, not you, bob')
print ("The smallest name previously entered is :", smallest)
print("The largest name previously entered is :", largest)
非常感谢您的帮助
答
试图将输入转化为int
,如果它工作的一个数字。
try:
user_number = int(input("Enter a name: "))
except ValueError:
print("That's a good name!")
答
您可以检查用户输入只包含字母:
if not new_name.isalpha():
print 'Only letters are allowed!'
注:空白也被视为禁止的字符。