So I have been learning python for I guess 10 days or so and I came across some weird behavior by python.
Code snippets and output images below:
#calculator
def add(n1,n2):
"""Adds two numbers"""
return n1 + n2
def subtract(n1,n2):
"""Subtracts two numbers"""
return n1 - n2
def multiply(n1,n2):
"""Multiplies two numbers"""
return n1 * n2
def divide(n1,n2):
"""Divides two numbers"""
return n1 / n2
#we do not add paranthesis because we want to store the names of functions in the dictionary
#we do not want to assign the function and trigger a call for execution itself. Hence only the name of the function will suffice.
operations = {
'+' : add,
'-': subtract,
'*': multiply,
'/': divide,
}
num1 = int(input("What is this first number you want to enter ?\n"))
num2 = int(input("What is this second number you want to enter ?\n"))
for operation_symbols in operations:
print(operation_symbols)
operation_symbol = input("Pick a symbol from the list above for your calculations")
answer = operations[operation_symbol]
answer(num1,num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
When I write this code: my output is the image below: output
However, when I make the following changes
#calculator
def add(n1,n2):
"""Adds two numbers"""
return n1 + n2
def subtract(n1,n2):
"""Subtracts two numbers"""
return n1 - n2
def multiply(n1,n2):
"""Multiplies two numbers"""
return n1 * n2
def divide(n1,n2):
"""Divides two numbers"""
return n1 / n2
#we do not add paranthesis because we want to store the names of functions in the dictionary
#we do not want to assign the function and trigger a call for execution itself. Hence only the name of the function will suffice.
operations = {
'+' : add,
'-': subtract,
'*': multiply,
'/': divide,
}
num1 = int(input("What is this first number you want to enter ?\n"))
num2 = int(input("What is this second number you want to enter ?\n"))
for operation_symbols in operations:
print(operation_symbols)
operation_symbol = input("Pick a symbol from the list above for your calculations")
operation_function = operations[operation_symbol]
answer = operation_function(num1,num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
The output I get is the desired one: desired output of calculator from above code snippet
I wanted to know why this happens. I have no idea what is the deal with my code. Thanks and Regards.