简体   繁体   English

如何在我的 python 脚本中重新启动 main() function? 无论我添加什么输入,程序都会重新启动

[英]How do I restart the main() function in my python script? The program restarts no matter what input I add

How do I ensure that when "Y" "y" "yes" is input the program restarts?如何确保输入“Y”“y”“yes”时程序重新启动? Then If anything else is input then the program ends?那么如果输入了其他任何内容,那么程序就结束了吗? At the moment if anything is input (including nothing at all) and I press Enter, the program will restart regardless.目前,如果输入任何内容(包括什么都没有)并且我按 Enter 键,程序将无论如何都会重新启动。

The code I have written to do this is below, it is all wrapped within a main() function:我为此编写的代码如下,它全部包含在 main() function 中:

def main():

# Main program code here

# Ask the player whether they want to retry
    if display == wordChosen:
      tryAgain = str(input("Try again: (Y = yes / N = no)"))
      tryAgain = tryAgain.lower()
      if tryAgain == "Y" or "y" or "yes":
        print(tryAgain) # for testing just to see whether its being picked up
        main()
      else:
        exit

main()

You can change your if statement to this: if tryAgain == "y" or tryAgain == "yes": since you already converted tryAgain input to lowercase, no need to check if its "Y" since it will never be uppercased.您可以将 if 语句更改为: if tryAgain == "y" or tryAgain == "yes":因为您已经将 tryAgain 输入转换为小写,所以无需检查其是否为“Y”,因为它永远不会大写。 And the line if tryAgain == "Y" or "y" or "yes": Checks if tryAgain is "Y" and then checks if "y" is true or "yes" is true, not if tryAgain is "y" or "yes", and as far as I know non-empty strings are always true. if tryAgain == "Y" or "y" or "yes":检查 tryAgain 是否为 "Y",然后检查 "y" 是否为真或 "yes" 是否为真,而不是 tryAgain 是否为 "y" 或“是”,据我所知,非空字符串总是正确的。

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

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