首页 > 解决方案 > Python:根据 IF 语句输出,在自身之外执行不同的代码

问题描述

如果 my_input == "n" 我想让我的程序再次循环,这很好。但是,如果我的 else 语句为 True,我不希望它再次运行整个程序,而只是在 my_input 变量处“开始”。

我怎样才能做到这一点?

def name_user_validation():
    while True:
        full_name = input("What is your name? ")
        print(f"Hello {full_name}, nice to meet you.")
        full_name.split()
        print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
    
        my_input = input("Is that right? (y/n) ")
        if (my_input == "y"):
            print("Great!")
            break
        elif my_input == "n":
            print("Oh no :(")
        else:
            print("Invalid input, try again.")
name_user_validation()

标签: pythonif-statementwhile-loop

解决方案


我误解了您的问题,我可能会稍微重构您的代码,因此您可以摆脱 while 循环并在需要时使用递归函数调用返回,

类似于下面的东西

def name_user_validation():
    full_name = input("What is your name? ")
    print(f"Hello {full_name}, nice to meet you.")
    full_name.split()  # This line actually doesn't do anything
    print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")

    if not accept_input():
        name_user_validation()


def accept_input():
    my_input = input("Is that right? (y/n) ")
    if my_input == "y":
        print("Great!")
        return True
    elif my_input == "n":
        print("Oh no :(")
        return False
    else:
        print("Invalid input, try again.")
        accept_input()


name_user_validation()

推荐阅读