python - 将一组while循环变成一个大循环

标签 python loops while-loop

我如何将这组 while 循环变成一个大的 while 循环,其中每个测试都用于验证用户名?任何帮助,将不胜感激!

username = input("Please enter a username: ")


while len(username) < 8 or len(username) > 15:
    print("Username must be between 8 and 15 characters long.")
    username = input("Please enter a username: ")
while username.isalpha() == False:
    print ("Username can only contain alphanumeric characters.")
    username = input("Please enter a username: ")
while username.islower() == False:
    print ("Usernames must contain at least one lowercase character")
    username = input("Please enter a username: ")
while username.isupper() == False:
    print ("Usernames must contain at least one uppercase character")
    username = input("Please enter a username: ")
while username.isnumeric() == False:
    print ("Usernames must contain at least one numeric character")
    username = input("Please enter a username: ")
    firstch = username([0])
    lastch = username([-1])
while firstch.isnumeric == True:
    print ("The first character in a username cannot be a digit")
    username = input("Please enter a username: ")
while lastch.isnumeric == True:
    print ("The last character in a username cannot be a digit")
    username = input("Please enter a username: ")
    break

最佳答案

除非你完全有意为每一次检查发出警告(我可能只是验证它,然后一次性显示规则)你可以使用类似的东西:

from unicodedata import category

username = input('Please enter a username: ')

valid = bool(
    # Length check
    8 <= len(username) <= 15
    # No digits for first or last character 
    and not username[0].isdigit() 
    and not username[-1].isdigit() 
    # Consists of only uppercase, lowercase or digits - but at least one of each
    and {'Lu', 'Ll', 'Nd'} == {category(ch) for ch in username}
)

关于python - 将一组while循环变成一个大循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362491/

相关文章:

python - Pandas 中的动态产品

Jquery:为什么一个有效而另一个无效?

c - 当我为 & records[*Count].source 输入值时,.exe 崩溃

javascript - Jquery,同时,每个: how to test if all :selected is not 0

python - 在 Python 中动态增加类变量

python - 支持 argparse 中的枚举参数

python - 检查数据帧组是否包含提供列表中的子字符串(不区分大小写)

java - Java 中的循环从字符串中获取 2 个值

C++ 加密 ascii 值打印数组中的返回键

c - 双 while 循环链表导致无限循环