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

时间:2016-04-01 17:36:00

标签: 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

6 个答案:

答案 0 :(得分:3)

除非您完全打算对每一次检查发出警告(我可能只是验证它,然后一次显示规则),您可以使用以下内容:

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}
)

答案 1 :(得分:2)

将整个输入过程放入一个while循环中,并使用单个if语句检查条件:

username_is_valid = False

while not username_is_valid:

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

    if len(username) < 8 or len(username) > 15:
        print("Username must be between 8 and 15 characters long.")
        continue
    if not username.isalpha():
        print ("Username can only contain alphanumeric characters.")
        continue
    if not username.islower():
        print ("Usernames must contain at least one lowercase character")
        continue
    if not username.isupper():
        print ("Usernames must contain at least one uppercase character")
        continue
    if not username.isnumeric():
        print ("Usernames must contain at least one numeric character")
        continue

    firstch = username([0])
    lastch = username([-1])

    if firstch.isnumeric:
        print ("The first character in a username cannot be a digit")
        continue
    if lastch.isnumeric:
        print ("The last character in a username cannot be a digit")
        continue

    break

print("Username is valid!")

修改

我看到你的一些条件是错的。例如:

对于相同的输入,

username.islower()username.isupper()永远不会成立。看看@ John的解决方案答案。

正如@zondo所说,你也可以简化你的布尔检查(请将你的条件与我的比较)

答案 2 :(得分:2)

checks = [
    (lambda: 8 <= len (username) <= 15, 'Username must be between 8 and 15 characters long.'),
    (lambda: username.isalpha (), 'Username can only contain alphanumeric characters.'),
    # And so on, you get the idea, it is very simple to expand this list and you can even make it dynamic.
]

while True:
    username = input ('Please enter a username: ')
    for check in checks:
        if not check [0] ():
            print (check [1])
            break
    else:
        break

答案 3 :(得分:1)

在我看来,更合理的结构方式是

username_is_valid = False

while not username_is_valid:
    username = input("Please enter a username: ")
    if len(username) < 8 or len(username) > 15:
        print("Username must be between 8 and 15 characters long.")
    elif username.isalpha() == False:
        print ("Username can only contain alphanumeric characters.")
    else:
        username_is_valid = True

你的一些逻辑也没有以你想要的方式工作,例如username.isupper()应写成

import string
if not any(c in username for c in string.ascii_uppercase):
    print("username needs one uppercase character")

这是一个更完整的解决方案

username_is_valid = False

while not username_is_valid:
    username = input("Please enter a username: ")
    if len(username) < 8 or len(username) > 15:
        print("Username must be between 8 and 15 characters long.")
    elif not username.isalnum():
        print("Username can only contain alphanumeric characters.")
    elif not any(c.islower() for c in username):
        print("Usernames must contain at least one lowercase character")
    elif not any(c.isupper() for c in username):
        print("Usernames must contain at least one uppercase character")
    elif not any(c.isdigit() for c in username):
        print("Usernames must contain at least one numeric character")
    elif username[0].isdigit():
        print("The first character in a username cannot be a digit")
    elif username[-1].isdigit():
        print("The last character in a username cannot be a digit")
    else:
        username_is_valid = True

答案 4 :(得分:0)

def check_len(name):
    return (len(name) >= 8) and (len(name) <= 15)

conds = [check_len, str.isalpha, str.islower, ...] #conditions for the name in general
msgs = ["Username must be between 8 and 15 characters long.", \
        "Username can only contain alphanumeric characters.", \
        ...]  #corresponding error messages

parsed = False
while True:
    uname = input('Please enter username: ')
    for i in range(len(conds)):
        func = conds[i]  
        if not func(uname):  # call each function on the username
            print(msgs[i])   # print the corresponding err msg
            break
    else:
        parsed = True  # initial checks are done

    if not parsed:   # else restart the loop
        continue

    if uname[0].isnumeric() or uname[-1].isnumeric():
        print('No digits in first or last character!")
        parsed = False
        continue

答案 5 :(得分:0)

您的验证存在一些问题,例如username.islower()断言整个字符串较低,而不仅仅是字符串中的字符。可以通过扫描any(c.islower() for c in username)等字符串来修复这些问题。然后,每次提示输入用户名时都不检查所有条件,你根本就没有验证它。

这是一个while循环,通过记录输入错误来跟踪故障。它一次性为用户提供所有坏消息,以便解决所有问题。它的可读性更高。

while 1:
    username = input("Please enter user name: ")
    errs =  []
    if len(username) < 8 or len(username) > 15:
        errs.append("be between 8 and 15 characters long")
    if not username.isalnum():
        errs.append("only contain alphanumeric characters")
    if not any(c.lower() for c in username):
        errs.append("contain at least one lowercase character")
    if not any(c.upper() for c in username):
        errs.append("contain at least one uppercase character")
    if not any(c.isnumeric() for c in username):
        errs.append("contain at least one numeric character")
    if username[0].isnumeric():
        errs.append("not have digit as first character")
    if username[-1].isnumeric():
        errs.append("not have digit as last character")
    if errs:
        errs.insert(0, "Invalid. Username must...")
        print("\n  ..".join(errs))
    else:   
        break