我不明白为什么我需要输入“q”n次的问题生成,退出程序

2024-10-01 02:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道为什么我必须输入qn次生成的问题才能退出程序,当我只输入q一次时,我应该怎么做才能使程序立即关闭

    greetings = input("Hello, what should i call you? ")
    
    
    def generate_again_or_quit():
        while True:
            option = input("Press any key to generate another question or Q to exit" ).lower()
            if option == "q":
                break
            generate_questions()
            
    def generate_questions():
        print(random_questions_dict.get((random.randint(1, 30))))
        generate_again_or_quit()
    while True:
        greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
        
        if greetings2 == "yes":
            generate_questions()
            break
            
        elif greetings2 == "no":
            print("See you later...")
            break
        else:
            print("Please answer with yes or no")
            continue

Tags: orto程序youinputdefgeneratequit
1条回答
网友
1楼 · 发布于 2024-10-01 02:23:11

如注释所示,选择迭代或递归。下面是一个递归示例

import random

random_questions_dict = {1: "why", 2: "what", 3: "when", 4: "which", 5: "how"}

def generate_questions():
    print(random_questions_dict.get((random.randint(1, 5))))
    option = input("Press any key to generate another question or Q to exit" ).lower()
    if option == "q":
        return
    generate_questions()


greetings = input("Hello, what should i call you? ")

while True:
    greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
    
    if greetings2 == "yes":
        generate_questions()
        break
        
    elif greetings2 == "no":
        print("See you later...")
        break
    else:
        print("Please answer with yes or no")
        continue

相关问题 更多 >