关于如何循环回程序的开头:如何循环回程序的开头 – Python

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

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
#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" :

....


将整个代码包装成循环:

1
while True:

每隔一行缩进4个字符。

每当您想"从头重新开始"时,请使用statement

1
continue

无论何时想要终止循环并继续循环,都要使用

1
break

如果要终止整个程序,在代码开头import sys(在while True:之前 - 不用重复import! - ),并且每当要终止程序时,请使用

1
sys.exit()


如果用户想要再次启动,您只需要调用该函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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()