简体   繁体   中英

I am a little bit confused about creating kinda a loop

I'am at the beginning of my road into python, this is my first creation in python and I have a little bit of a problem, I've created a basic calculator, it works kinda good, but my question is how can I make the calculator ask again for num1 and operator after I run it, I mean, I run it, it works, but after the calculation is done, I have to rerun it in order to ask for num1 and op. How can I make it ask again for num1 and op when you press a key after a calculation is done. This is my first time asking here and if my question is too basic, I'm sorry.

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")

Run the calculator within a while loop to rerun it continuously.

The simplest way is:

while True:
    #calculator code

Or you can have a condition that ends the program:

keep_running = True

while keep_running:
    #calculator code

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

This is just a simple example but hopefully it breaks down the concept for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM