python中if,else问题

这是这两段代码是检测强弱密码的,要求至少8位字符且必须包含大小写字母和数字。
第一段代码,没有使用else语句,执行正常。

import re
def check(password):
    num = len(password)
    pwRegex_1 = re.compile(r'[A-Z]+')
    pwRegex_2 = re.compile(r'[a-z]+')
    pwRegex_3 = re.compile(r'\d+')
    p1 = pwRegex_1.search(password)
    p2 = pwRegex_2.search(password)
    p3 = pwRegex_3.search(password)
    if num < 8:
        print("密码长度必须达到8位或以上。")

    if p1 is None:
        print("请至少输入一个大写字母!")

    if p2 is None:
        print("请至少输入一个小写字母!")

    if p3 is None:
        print("请至少输入一个数字!")

    if num >= 8 and p1 is not None and p2 is not None and p3 is not None:
        print("你输入的密码可以使用!")
        return True
while True:
    pw = input("请输入密码:")
    if check(pw) is True:
        break

第二段代码,使用else语句,会出问题,不知道是不是BUG,
代码在执行完if语句后,居然还能执行else语句,很奇怪。
代码如下:

import re
def check(password):
    num = len(password)
    pwRegex_1 = re.compile(r'[A-Z]+')
    pwRegex_2 = re.compile(r'[a-z]+')
    pwRegex_3 = re.compile(r'\d+')
    p1 = pwRegex_1.search(password)
    p2 = pwRegex_2.search(password)
    p3 = pwRegex_3.search(password)
    if num < 8:
        print("密码长度必须达到8位或以上。")

    if p1 is None:
        print("请至少输入一个大写字母!")

    if p2 is None:
        print("请至少输入一个小写字母!")

    if p3 is None:
        print("请至少输入一个数字!")

    else:
        print("你输入的密码可以使用!")
        return True
while True:
    pw = input("请输入密码:")
    if check(pw) is True:
        break

猜你喜欢

转载自blog.csdn.net/qq_20667737/article/details/86615426