2017-06-06 44 views
-5

我的導師已責成我做一個「ID打印機」我想使程序通過這樣它不會接受但輸入姓名時,不接受整數整體字符串。我的代碼如下。「而User_Name的!= STR()」將不接受字符串

User_Name = "" 
def namechecker(): 
    print("Please Input Your name") 
    User_Name = str(input(":")) 
    while User_Name == "": 
     print("Please input your name") 
     User_Name = str(input(":")) 


    while User_Name != str(): 
     print("Please use characters only") 
     print("Please input your name") 
     User_Name = input (":") 

print("Thankyou, ", User_Name) 
namechecker() 
+1

你根本無法做到'STR()'不帶參數。目前還不清楚你想要做什麼。 –

+3

'STR()'返回一個空字符串,它不是類型檢查的方法。 –

+0

你能告訴我如何改進? –

回答

1

你的問題很不清楚。閱讀後,我認爲你想獲得一個只有字母字符的用戶名。您可以使用str.isalpha爲:

def getUserName(): 
    userName = '' 
    while userName == '' or not userName.isalpha(): 
     userName = input('Please input your name: ') 
     if not userName.isalpha(): 
      print('Please use alphabet characters only') 
    return userName 

userName = getUserName() 
print('Thank you, {}'.format(userName)) 
+0

我會在哪裏放呢? –

0

如果你想保持與您檢查數字的想法,你也可以檢查一個字符串只包含str.isdigit()位

篩選:

def namechecker(): 
    User_Name = "" 
    while True: 
    User_Name = input("Please input your name: ") # input will always be a string 
    if User_Name.isdigit(): # check if the string contains only digits // returns True or False 
     print("Please use chracters only") 
     continue # stay inside the loop if the string contains only digits 
    else: break # leave the loop if there are other characters than digits 
    print("Thankyou, ", User_Name) 

namechecker() 

注意,此代碼將只要求其他輸入,如果給定的字符串包含只有數字。如果你想確保一個字符串只包含字母字符,你可以用string.isalpha()

def namechecker(): 
    User_Name = "" 
    while True: 
    User_Name = input("Please input your name: ") 
    if not User_Name.isalpha(): 
     print("Please use chracters only") 
     continue 
    else: break 

    print("Thankyou, ", User_Name) 
namechecker() 

這將這樣的伎倆,並沒有數字被允許在你的輸入工作。但是,您應該閱讀關於Built-in Types的文檔。

相關問題