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

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

我在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" :

.....

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

while True:

每隔一行缩进 4 个字符。

只要你想"restart from the beginning",使用语句

continue

每当你想终止循环并在它之后继续时,使用

break

如果你想终止整个程序,import sys 在代码的开头( while True: 之前——重复 import!-) 每当你想终止程序时,使用

sys.exit()

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

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()