本问题已经有最佳答案,请猛点这里访问。
我在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" :
....
将整个代码包装成循环:
1while True:
每隔一行缩进4个字符。
每当您想"从头重新开始"时,请使用statement
1continue
无论何时想要终止循环并继续循环,都要使用
1break
如果要终止整个程序,在代码开头import sys(在while True:之前 - 不用重复import! - ),并且每当要终止程序时,请使用
1sys.exit()
我应该把首字母放在哪里? 我希望它回到哪里?
@nitrogirl,确切地说 - 大概是在import语句或其他初始化之后,你不想一遍又一遍地重复。
非常感谢! 它很棒
如果用户想要再次启动,您只需要调用该函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def 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()