Basic Python:为什么 While 循环需要调用它两次?

Basic Python: Why While Loop Demands To Call It Twice?

为了刷新我的基础Python 中断几年后,我正在尝试通过学者技术解决密码验证问题。根据我的任务,我必须(1)写一个函数; (2) 使用我预先编写的一些其他功能; (3) 对每个函数使用不同的技术; (4) 使用while循环逐个检查某些字符的密码; (5) 不要使用正则表达式等高级技术,也不要编写测试。

问题是:如果我第一次输入一个应该满足条件 b "char_in_str(inp) != True" 的字符串(例如,通过在命令行中键入 j8& )我得到 no char,但如果我第二次输入完全相同的 j8& ,它会按预期工作,我会看到 YES

我的代码中缺少什么?如果您指出要查看的位置而不是编写一个简单的解决方案,那就太好了。如果我无法修复代码,我宁愿另外寻求解决方案))

这是我的代码:

# -*- coding: utf-8 -*-
       
def num_in_str(inp):
    return any(s.isdigit() for s in inp)

# it should be stopped on j
# it should pass j8

def char_in_str(inp):
    set_s = set(inp)
    set_ch = {"№", "#", "%", "!", "$", "@", "&", "*"}
    for s in set_s:
        if s in set_ch:
            return True
        else: 
            return False

# it should be stopped on j8
# it should pass j8&


def password():
    inp = input("Please enter your password here: ")
    a = num_in_str(inp) != True
    b = char_in_str(inp) != True

    incorrect = (a or b)
    while incorrect:
        if a:
            print("no num")    
            inp = input("here: ")
            break
        elif b:
            print("no char")
            inp = input("here: ")
            break
        
    print("YES")
                          

password()

我在终端上看到:

Please enter your password here: j8&
no char
here: j8&
YES

对于此任务,我使用 Visual Studio 代码(这是先决条件)。我平时不怎么用,不知道有没有自己的特点影响效果。

看看你的功能。你读inp,你评价它。然后,在那个毫无意义的 while 循环中,打印一个结果,获取另一个输入,然后退出循环,打印“YES”并退出。您需要恰好请求输入一次,并且需要在循环内:

def password():
    while True:
        inp = input("Please enter your password here: ")

        if not num_in_str(inp):
            print("no num")    
        elif not char_in_str(inp):
            print("no char")
        else:
            break
        
    print("YES")

您的 char_in_str 函数只检查第一个字符。更改最后几行:

def char_in_str(inp):
    set_ch = "№#%!$@&*"
    for s in inp:
        if s in set_ch:
            return True
    return False