# I need help fixing this, i need to make the operations shorter, but they need to still work. BTW I am using python 3

+3 votes
asked Feb 13, 2021
if operation == "add":
print(num1, "+", num2,"=", num1 + num2)
elif operation == "subtract":
print(num1, "-", num2,"=", num1 - num2)
elif operation == "multiply":
print(num1, "*", num2,"=", num1 * num2)
elif operation == "divide":
print(num1, "/", num2,"=", num1 / num2)
else:
print("Not a valid operation.")

## 2 Answers

0 votes
answered Feb 13, 2021 by (140 points)
def calcule(a, b, operator):
operations = {"add":a+b, "subt":a-b, "mul":a*b, "div":a/b}
symbole = {"add":'+', "subt":'-', "mul":'*', "div":'/'}

try:
# if the key doesn't exist, it will will throw keyError
print(a, symbole[operator], b, " = ", operations[operator])
except KeyError:
print("unknown operator")

# I'm a beginer too. So of you see a bad pratice in my code, don't hesitate to tell me.

# another error (like) zeroDivisionError can happen too. So you have to upgrade the code
0 votes
answered Feb 13, 2021 by (2,870 points)

I don't think there is a shorter way to write it, though Here are two ways to execute it:

## Method 1:

Make a calculate function.

```def calculate():#This makes a function that asks for the numbers and what to use on them.
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a second number: "))
operation = input("What do you want to do? ")
if operation == "add":
print(num1, "+", num2,"=", num1 + num2)
elif operation == "subtract":
print(num1, "-", num2,"=", num1 - num2)
elif operation == "multiply":
print(num1, "*", num2,"=", num1 * num2)
elif operation == "divide":
print(num1, "/", num2,"=", num1 / num2)
else:
print("Not a valid operation.")

calculate()#Now all you have to do is call the function like this whenever you want to use it in the code.```

## Method 2:

Give the function parameters instead of input variables.

```def calculate(num1,num2,operation):#This gives the function parameters to use as it operates.
if operation == "add":
print(num1, "+", num2,"=", num1 + num2)
elif operation == "subtract":
print(num1, "-", num2,"=", num1 - num2)
elif operation == "multiply":
print(num1, "*", num2,"=", num1 * num2)
elif operation == "divide":
print(num1, "/", num2,"=", num1 / num2)
else:
print("Not a valid operation.")

calculate(3,4,"add")#now Whenever you call the function in the code, you can give it instructions for what to do.
calculate(3,4,"subtract")
calculate(3,4,"multiply")
calculate(3,4,"divide")
calculate(3,4,"jeff")```