我是一個非常新的程式員。剛開始使用 Python。本質上,我必須撰寫一個接受用戶名輸入的程式,并進行一些驗證。用戶名必須在 5-10 個字母字符之間。我正在獲取代碼來測驗字串的長度,但我沒有得到它來測驗字母字符。我究竟做錯了什么?
correct = True
while correct:
username = input('Enter a username that has only alphabetical characters and is between 5 and 10 characters long:')
if username.isalpha:
while len(username) < 5:
print('Invalid username! Please try again.')
username = input('Enter a username that has only alphabetical characters'
' and is between 5 and 10 characters long:')
if username.isalpha:
while len(username) > 10:
print('Invalid username! Please try again.')
username = input('Enter a username that has only alphabetical characters'
' and is between 5 and 10 characters long:')
correct = False
else:
print('Username accepted.')
uj5u.com熱心網友回復:
isalpha是一個函式,順便說一句,你需要呼叫它這么做isalpha(),而不是
如果你想了解更多關于 python 字串https://docs.python.org/3/library/string.html,我建議閱讀官方 python 檔案以獲得更好的學習
uj5u.com熱心網友回復:
由于這是在評論部分中提到,你錯過了括號()的isalpha。
我還建議像這樣編輯代碼:
while True:
username = input('Enter a username that has only alphabetical characters and is between 5 and 10 characters long:')
if username.isalpha() and 5 <= len(username) <= 10:
print('Username accepted.')
break
else:
print('Invalid username! Please try again.')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312715.html
