我是个非常新的程序员。刚从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.')发布于 2021-10-07 18:55:28
正如注释部分所提到的,您忽略了括号() of 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.')发布于 2021-10-07 18:50:52
isalpha是一个函数,顺便说一句,您需要调用它,isalpha()也需要调用它。
如果您想了解更多关于python https://docs.python.org/3/library/string.html的知识,我建议您阅读官方python文档以获得更好的学习。
https://stackoverflow.com/questions/69486334
复制相似问题