首页 > 解决方案 > 基础 Python:为什么 While 循环需要调用两次?

问题描述

为了在休息几年后刷新我的基本 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 Code(这是先决条件)。我不正常使用它,也不知道它是否有自己的特性影响结果。

标签: pythonwhile-loop

解决方案


看你的功能。你阅读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

推荐阅读