我已经在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" :
...
答案 0 :(得分:2)
将整个代码包装成循环:
while True:
将每隔一行缩进4个字符。
无论何时你想从头开始重新开始#34;,都要使用声明
continue
每当您想要终止循环并继续循环之后,请使用
break
如果你想终止整个程序,import sys
代码的开头(之前 while True:
- 不要重复使用import
! - )并且只要您想终止程序,请使用
sys.exit()
答案 1 :(得分:1)
如果用户想要重新开始,您只需要调用该函数:
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()