Reputation: 1
I was trying to make a quick little user-input calculator but to do that I need the user to decide what operator to use. I tried to make the user-input for the operator a string but that obviously didn't work. I tried it as an integer too but still had no luck. So I'm confused about what it is that I'm supposed to do.
so far I only have this and it shows an error:
num1 = int(input("What is your first number?: "))
num2 = int(input("What is your second number?: "))
op = (input("Enter an operator: ")
print(num1 + op + num2)
SOLVED
Upvotes: 0
Views: 821
Reputation: 2602
The cleanest safe way to do this is by storing the operators as functions in a dictionary:
from operator import *
num1 = int(input("What is your first number?: "))
num2 = int(input("What is your second number?: "))
op = input("Enter an operator: ")
ops = {
"+": add, # from the operators module
"-": sub,
"/": div,
"*": mul
}
print(ops[op](num1,num2))
Upvotes: 1
Reputation: 89
you could create some if statements like this:
if op == '+':
print(num1 + num2)
if op == '-':
print(num1 - num2)
Just do the same thing for multiplying and dividing
Upvotes: 0