有没有一种方法可以在while循环中简化isalpha,len函数



我是一个非常新的程序员。刚开始学习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.')

相关内容

  • 没有找到相关文章

最新更新