我確信答案就在我面前,但是當我輸入正確的條件時,我似乎無法弄清楚如何修復我的第一個 if 陳述句的回傳值。
create_password = input("Enter password here: ")
if len(create_password) > 6 and create_password.isdigit() > 0:
print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
print("Password must include a number")
else:
print("Your password sucks")
假設我輸入了elephant100,我試圖得到提示“您的帳戶已準備好!”。但令我沮喪的是,它列印出“密碼必須包含一個數字”,我不知道為什么。我的其他條件與正確的輸入匹配,但這是唯一一個不起作用的條件。
uj5u.com熱心網友回復:
.isdigit()True如果所有字符都是數字,則方法回傳,否則回傳False。因此False在這種情況下它會回傳,因為您的字串包含 e、l、p 等字母。因此該陳述句print("Your account is ready!")將永遠不會被執行。
uj5u.com熱心網友回復:
結果我需要使用 isalnum()、isnumeric() 和 isalpha() 來解決我的問題。感謝 Muhammed Jaseem 幫助我解決這個問題!這是我修改后的代碼。
if create_password.isnumeric() == True:
print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
print("Your account is ready!")
else:
print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/385834.html
