I decided to start learning python recently and I've been watching a youtube course to get introduced to the language. I decided to try and make a simple calculator that can add, subtract, multiply, and divide multiple numbers in order to practice what I learned so far.
Here's the code for the calculator:
num1 = float(input("Enter a number: "))
operation = input("Enter an operation (+,-,*,/): ")
if operation != "+" and operation != "-" and operation != "*" and operation != "/":
print("Invalid Operator")
exit()
num2 = float(input("Enter another number: "))
def add(num1,num2):
global num1
num1 += num2
return num1
def subtract(num1,num2):
num1 -= num2
return num1
def multiply(num1,num2):
num1 *= num2
return num1
def divide(num1,num2):
num1 /= num2
return num1
while operation == "+" or operation == "-" or operation == "*" or operation == "/" or operation == "=":
if operation == "+":
result = add(num1,num2)
elif operation == "-":
result = subtract(num1,num2)
elif operation == "*":
result = multiply(num1,num2)
elif operation == "/":
result = divide(num1,num2)
elif operation == "=":
print(result)
break
if operation != "+" and operation != "=" and operation != "-" and operation != "*" and operation != "/":
print("Invalid Operator")
exit()
operation = input("Enter an operation (+,-,*,/, or =): ")
if operation == "=":
print("Answer: " + str(result))
break
num2 = float(input("Enter another number: "))
print(num1)
However, my issue is that the variable "num1" isn't getting assigned a new value through assignment operators. The way I planned for this to work was for num1 to keep getting assigned the sum, difference, multiple, or quotient, of the previous two numbers depending on what operation the user wanted (ex. adding, subtracting, etc.) and how many numbers the user wanted to add, subtract, etc. Instead, it remains the value that the user inputs.
I included the print(num1) statement at the end of my code just to see what number num1 takes when I'm finished running the program.
Here's an example of what happens when I run the program.
Enter a number: 2
Enter an operation (+,-,*,/): +
Enter another number: 2
Enter an operation (+,-,*,/, or =): +
Enter another number: 2
Enter an operation (+,-,*,/, or =): =
Answer: 4.0
2.0