有没有办法在while循环中简化isalpha,len函数?
Is there a way to simplify isalpha, len function, in a while loop?
我是一个非常新的程序员。刚从 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.')
isalpha
是一个函数,顺便说一句,你需要调用它
所以 isalpha()
而不是
如果你想了解更多关于python字符串https://docs.python.org/3/library/string.html,我建议阅读官方python文档以便更好地学习
正如评论区所说,你漏掉了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.')
我是一个非常新的程序员。刚从 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.')
isalpha
是一个函数,顺便说一句,你需要调用它
所以 isalpha()
而不是
如果你想了解更多关于python字符串https://docs.python.org/3/library/string.html,我建议阅读官方python文档以便更好地学习
正如评论区所说,你漏掉了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.')