0

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

2 回答 2

1

isalpha是一个函数,顺便说一句,您需要调用它,isalpha()而是这样做

如果你想了解更多关于 python 字符串https://docs.python.org/3/library/string.html,我建议阅读官方 python 文档以便更好地学习

于 2021-10-07T18:50:52.813 回答
0

正如评论部分中提到的那样,您错过()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-07T18:55:28.153 回答