2016-11-25 78 views
0

對於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) 

非常感謝您的幫助

回答

1

試圖將輸入轉化爲int,如果它工作的一個數字。

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

您可以檢查用戶輸入只包含字母:

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

注:空白也被視爲禁止的字符。