我正在編寫一個提示輸入用戶名的腳本。用戶名的長度必須是 3 個或更多且 10 個或更少的字符。我想使用 while 重構代碼,而不是重復提示。def hint_username(username): if len(username) < 3: print("Invalid Username, minimum of 3 characters") myUser = input("Please enter username: ") hint_username(myUser) elif len(username) >10: print("Invalid Username, maximum of 10 characters") myUser = input("Please enter username: ") hint_username(myUser) else: print("Valid Username")myUser = input("Please enter username: ")hint_username(myUser)
1 回答

慕尼黑8549860
TA貢獻1818條經(jīng)驗 獲得超11個贊
while您可以使用循環(huán)來執(zhí)行此操作。我不建議遞歸調用函數(shù)來驗證用戶輸入。
def invalid_username(username):
return not 3 <= len(username) <= 10
myUser = input("Please enter username: ")
while invalid_username(myUser):
myUser = input(
"Invalid username! Username must be 3 to 10 characters.\n"
"Please enter username: "
)
print("Valid Username")
添加回答
舉報
0/150
提交
取消