我对创建一个循环有点困惑

2024-03-29 12:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开始我的python之路,这是我第一次用python创作,我有一个小问题,我已经创建了一个基本的计算器,它工作得不错,但我的问题是,在我运行它之后,我如何让计算器再次问num1和运算符,我的意思是,我运行它,它工作得很好,但在计算完成之后,我必须重新运行它才能请求num1和op。当计算完成后按一个键时,如何使它再次请求num1和op。 这是我第一次在这里提问,如果我的问题太简单,我很抱歉

import math
#creating our variables
num1 = float(input("Enter the first number: "))
op = input("Enter the operator: ")

#creating the calculator for simple calculations
if op == "+":
    num2 = float(input("Enter the second number: "))
    print(num1 + num2)
elif op == "-":
    num2 = float(input("Enter the second number: "))
    print(num1 - num2)
elif op == "*":
    num2 = float(input("Enter the second number: "))
    print(num1 * num2)
elif op == "/":
    num2 = float(input("Enter the second number: "))
    print(num1 / num2)

#creating the advanced calculations
elif op == "square":
    print(num1**2)
elif op == "cube":
    print(num1**3)
elif op == "square root":
    print(math.sqrt(num1))
elif op == "square number":
    num2 = float(input("Enter the second number: "))
    print(num1**num2)
elif op == "cube root":
    print(num1**(1/3))
else:
    print("Error, please enter a valid operator")

Tags: thecreatingnumberinputmathfloat计算器print
1条回答
网友
1楼 · 发布于 2024-03-29 12:15:37

while循环中运行计算器以连续重新运行它

最简单的方法是:

while True:
    #calculator code

或者您可以有一个结束程序的条件:

keep_running = True

while keep_running:
    #calculator code

    if input('Keep Computing? (yes/no) ').lower() == 'no':
        keep_running = False 

这只是一个简单的例子,但希望它能为您打破这个概念

相关问题 更多 >