r/PythonLearning • u/Superb_Screen_2484 • Jul 24 '25
this is my python calculating program
I'm started to learning python ....
70
Upvotes
r/PythonLearning • u/Superb_Screen_2484 • Jul 24 '25
I'm started to learning python ....
1
u/Labess40 Jul 24 '25
Nice code ! You can improve your code using this :
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
# Define the operations
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y if y != 0 else "Error: Division by zero is not allowed."
}
# Perform the calculation based on the operator
operation = operations.get(operator)
if operation:
result = operation(num1, num2)
return f"The result of {num1} {operator} {num2} is {result}."
else:
return "Error: Invalid operator."
This will directly interpret your operator as needed and you will remove your if else part.