首页 > 解决方案 > 如何用循环制作计算器,直到我选择中断

问题描述

我正在尝试构建一个带有循环的计算器,直到我选择打破它或结束它。你能建议吗?提前谢谢你,马克斯

new_operation = input("press enter to make a new operation or type the word exit to finish")

num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
while new_operation != ("no"):
    if op == ("+"):
        print (num1 + num2)
    elif op == ("-"):
        print (num1 - num2)
    elif op == ("*"):
        print (num1 * num2)
    elif op == ("/"):\
        print (num1 / num2)

else:
        print ("Invalid operation")
    new_operation = input("make a new operation")

标签: pythoncalculator

解决方案


您的代码看起来不错,但需要进行一些调整以使其成为“do while”循环类型的实现。

while True:
    num1 = int(input("Enter a number: "))
    op = input("Enter the operator: ")
    num2 = int(input("Enter a second number: "))
    if op == ("+"):
        print (num1 + num2)
    elif op == ("-"):
        print (num1 - num2)
    elif op == ("*"):
        print (num1 * num2)
    elif op == ("/"):\
        print (num1 / num2)
    else:
        print ("Invalid operation")
    new_operation = input("press enter to make a new operation or type the word exit to finish")
    if(new_operation == ("no")):
        break


推荐阅读