如何循环回到程序的开头 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28254807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:00:36  来源:igfitidea点击:

How to loop back to the beginning of a programme - Python

pythonloopspython-3.x

提问by nitrogirl

I've written a BMI calculator in python 3.4 and at the end I'd like to ask whether the user would like to use the calculator again and if yes go back to the beginning of the code. I've got this so far. Any help is very welcome :-)

我已经在 python 3.4 中编写了一个 BMI 计算器,最后我想问一下用户是否想再次使用计算器,如果是,请回到代码的开头。到目前为止我已经有了这个。非常欢迎任何帮助:-)

#Asks if the user would like to use the calculator again
again =input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")

while(again != "n") and (again != "y"):
    again =input("Please type a valid response. Would you like to try again? Please type y for yes or n for no-")

if again == "n" :
    print("Thank you, bye!")

elif again == "y" :

....

....

采纳答案by Alex Martelli

Wrap the whole code into a loop:

将整个代码包装成一个循环:

while True:

indenting every other line by 4 characters.

每隔一行缩进 4 个字符。

Whenever you want to "restart from the beginning", use statement

每当您想“从头开始”时,请使用语句

continue

Whenever you want to terminate the loop and proceed after it, use

每当您想终止循环并在其后继续时,请使用

break

If you want to terminate the whole program, import sysat the start of your code (beforethe while True:-- no use repeating the import!-) and whenever you want to terminate the program, use

如果你想终止整个程序,import sys在你的代码开始(之前while True:-没有重复使用的import- - !),只要你想终止程序,使用

sys.exit()

回答by Padraic Cunningham

You just need to call the function if the user wants to start again:

如果用户想重新开始,您只需要调用该函数:

def calculate():
    # do work
    return play_again()


def play_again():
    while True:
        again = input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")
        if again not in {"y","n"}:
            print("please enter valid input")               
        elif again == "n":
            return "Thank you, bye!"
        elif again == "y":
            # call function to start the calc again
            return calculate()
calculate()