迭代并打印错误消息

时间:2016-11-25 09:43:25

标签: python

对于一个python Bootcamp,我正在研究一个程序,它反复要求输入一个“名称”并打印出来。

当用户输入“bob”时,程序必须打印出“哦,不是你,bob!”,并打印出之前输入的最短和最长的名字。

如果用户输入的不是字符串(例如数字),程序必须打印出错误信息并继续再次询问姓名。

我不知道如何在用户输入int,float或其他内容而不是像'romeo'这样的字符串时打印出错误消息

请参阅下面我的计划:

 `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)

非常感谢您的帮助

2 个答案:

答案 0 :(得分:1)

尝试将输入转换为int,如果它是一个数字。

try:
   user_number = int(input("Enter a name: "))
except ValueError:
   print("That's a good name!")

答案 1 :(得分:1)

您可以检查用户输入是否仅包含字母:

if not new_name.isalpha():
    print 'Only letters are allowed!'

注意:空格也被视为禁用字符。