如何在测试失败后将功能分解到特定位置

How to break a function to a specific spot after a failed test

def joe():
    while True:
        name = ""
        answer = ""
        print("What is your name? ")
        name = input()
        if name != "Joe":
            continue
        print("What is your password? (it is a fish) ")
        answer = input()
        if answer == "swordfish":
            break
    print("nice job, Joe")
    
     joe()

如果我通过第一个语句并输入“Joe”,我将继续执行该函数,一切正常。但是如果我没有通过第二次测试,我就会中断函数并返回到“你叫什么名字?”功能的一部分。我怎样才能编写一个测试,在失败时让我回到“你的密码是什么”?而不是名称测试?

尝试结合使用 while True 和 `return 声明我的兄弟!

def joe():
    while True:
        print("What is your name? ")
        name = input()
        if name != "Joe":
            continue

        while True:
          print("What is your password? (it is a fish) ")
          answer = input()

          if answer == "swordfish":
            print("nice job, Joe")
            return
    
joe()

或者试试这个:

def joe():    
    name = ""
    answer = ""
    print("What is your name? ")
    name = input()
    if name == "Joe":
        print("What is your password? (it is a fish) ")
        answer = input()
    if answer == "swordfish":
        return print("nice job, Joe")
    
    joe()

joe()

为密码部分添加另一个 while 循环。

def joe():
    while True:
        print("What is your name? ")
        name = input()
        if name == "Joe":
            break
    while True:
        print("What is your password? (it is a fish) ")
        answer = input()
        if answer == "swordfish":
            break
    print("nice job, Joe")