【问题标题】:How to loop back to the beginning of a programme - Python [duplicate]如何循环回到程序的开头 - Python [重复]
【发布时间】:2025-12-14 14:55:02
【问题描述】:

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

....

【问题讨论】:

    标签: python loops python-3.x


    【解决方案1】:

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

    while True:
    

    每隔一行缩进 4 个字符。

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

    continue
    

    当你想终止循环并继续执行时,使用

    break
    

    如果你想终止整个程序,import sys 在你的代码开始处(之前 while True: -- 重复import 没用!-)以及任何时候你想要要终止程序,请使用

    sys.exit()
    

    【讨论】:

    • 我应该把首字母放在哪里?我想让它回到哪里?
    • @nitrogirl,确切地说——大概就在import 语句或您不想一遍又一遍地重复的其他初始化之后。
    • 非常感谢!效果很好
    【解决方案2】:

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

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

    【讨论】: