简体   繁体   English

程序完全跳过函数中的代码

[英]Program Completely Skipping Code in a Function

I have the following code, and after I input my name, it skips everything in the function and goes straight to the "Welcome..." part. 我有以下代码,输入我的名字后,它将跳过函数中的所有内容,并直接进入“ Welcome ...”部分。

import time

print("Hello.  Please enter your name, then press 'enter' ")
username = input()
print("Hello " + username)
time.sleep(2)


def game_tutorial_input():
    while True:
        tutorial_answer = input("Do you wish to see the tutorial?" 
                                "(y/n) ")
        if "y" in tutorial_answer:
            input("Great!  Press enter after each instruction to move" 
                  "onto the next one.")
            input("To answer each question, type one of the given" 
                  "options depending on what you want to select,"
                  " then press enter.")
            input("Wow, that was short tutorial!")
        else:
            print("Alright!")
            continue
        return


time.sleep(2)
print("Welcome, " + username + ", to Indiana")

How can I solve this problem? 我怎么解决这个问题?

Yep, just need to call the function 是的,只需要调用函数

import time

print("Hello.  Please enter your name, then press 'enter' ")
username = input()
print("Hello " + username)
time.sleep(2)


def game_tutorial_input():
    while True:
        tutorial_answer = input("Do you wish to see the tutorial?" 
                                "(y/n) ")
        if "y" in tutorial_answer:
            input("Great!  Press enter after each instruction to move" 
                  "onto the next one.")
            input("To answer each question, type one of the given" 
                  "options depending on what you want to select,"
                  " then press enter.")
            input("Wow, that was short tutorial!")
        else:
            print("Alright!")
            continue
        return

game_tutorial_input()

time.sleep(2)
print("Welcome, " + username + ", to Indiana")

As others have pointed out -- a couple of other issues, you're not returning anything in the function, your loop won't exit -- the while True wont ever 'break' 正如其他人所指出的-其他一些问题,您没有在函数中返回任何内容,您的循环不会退出-而True不会“中断”

you could consider something like this: 您可以考虑这样的事情:

# tutorial_answer is now True or False
tutorial_answer = input("Do you wish to see the tutorial?\n(y/n): ").lower() == "y"

or more complete handling: 或更完整的处理方式:

while True
    tutorial_answer = input("Do you wish to see the tutorial?\n(y/n): ").lower()
    if tutorial_answer == "y" or tutorial_answer == "n":
        break
    else:
        print("Sorry, I didn't understand that")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM