我现在是编程的新手,我不太基础。我试图在python中创建一个计算器,但它可以正常工作,但我无法重新运行它
我已经在某个站点上尝试过一些东西,但是一切都太复杂了,以至于我无法理解。
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
//i want the program to rerun itself here
else:
print("OK!!")
如果用户输入Y,我希望计算器重新启动。 详细的答案将不胜感激。谢谢
答案 0 :(得分:4)
要停止重复,请遍历该代码和break
:
while True: # Will start repeating here
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again != 'Y':
print("OK!! Exiting")
break # break to leave the loop
# It will loop automatically back to the top otherwise
答案 1 :(得分:1)
我们可以通过将其编写为函数并将其作为递归函数(如下所示)来实现。
def calculator():
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
calculator()
else:
print("OK!!")
calculator()
答案 2 :(得分:0)
您可以使用while loop
来再次运行代码,直到输入与Y
不同:
go_again = 'Y'
while go_again == 'Y':
num1 = input("Enter your 1st number: ")
num2 = input("Enter your 2nd number: ")
choose_ope = input("Choose your operator: ")
if choose_ope == '+':
print(float(num1) + float(num2))
elif choose_ope == '-':
print(float(num1) - float(num2))
elif choose_ope == '*':
print(float(num1) * float(num2))
elif choose_ope == '/':
print(float(num1) / float(num2))
go_again = input("Do you want to go again ? : Y/N\n")
if go_again == 'Y':
print("while loop will run again")
else:
print("program will exit")