2015-09-04 56 views
0

我在Python 3.4中的一個函數中有用戶輸入控件的問題。Python - 輸入控件

def input_name (*args): 
    name_output = "" 
    name_input = input ("Give first name: ") 
    if name_input.isalpha() and name_input[0].isupper() == True: 
     name_output += name_input 
     return (name_output) 
    else: 
     print ("Wrong, do it again") 
     input_name() 

name = input_name() 
print(name.lower()) 

我試圖抓住用戶輸入錯誤 - 這樣的名字必須是字母和第一個字母必須大寫。在將來的代碼中,我將使用小寫字母創建用戶登錄名,所以我試圖用小字母輸入登錄名的用戶名。有問題。

  1. 當我鍵入名稱冷杉時間好了,這是確定
  2. 當我鍵入首次名稱,爲1個小寫字母(名稱),然後我正確的(名字)寫它,它告訴我的錯誤,我不不明白爲什麼。你能告訴我,我的錯誤是什麼?

非常感謝您展示道路。 Mirek

+0

究竟是什麼錯誤? –

+0

錯誤是「AttributeError:'NoneType'對象沒有屬性'lower'」。 Cdonts的答案是偉大的,解決了這個問題,一切都在工作,但我正在學習編碼,所以現在我想知道,如果可以修復我的方式我張貼在這裏。 –

+0

'input_name()'之前缺少'return' –

回答

1

錯誤是由最後一行引起的。由於第一次輸入錯誤,函數返回None,所以name.lower()會引發異常。在這種情況下,我不會使用遞歸。

def input_name(): 
    while True: 
     name_input = input ("Give first name: ") 
     if name_input.isalpha() and name_input[0].isupper(): 
      return name_input 
     else: 
      print ("Wrong, do it again") 

name = input_name() 
print(name.lower()) 

希望它有幫助!