Calculator in python

Asked

Viewed 455 times

-1

I had a problem trying to make a calculator in Python, the first error code in the "Userselectionselect" bool. I’m having second thoughts on how to declare a method in a dictionary.

def Somar(a,b,r):
    return r == a+b
def Mult(a,b,r):
    return r == a*b
def Sub(a,b,r):
    return r == a - b
def Div(a,b,r):
    return r == a / b


print("Calculadora 1.0")
print("1 - Somar\n\n2 - Subtração\n\n3 - Divisão\n\n4 - Multiplicação\n\n ")
Select = int(input())
a = int(input("Digite o 1° Número "))
b = int(input("Digite o 2° Número "))
r = 0
UserSelection =  {1 : Somar(a,b,r),2 : Sub(a,b,r),3 : Div(a,b,r),4 : Mult(a,b,r)}
UserSelection[Select]()

print(r)

I also tried that way, but he doesn’t get the "a,b,r values".

def Somar(a,b,r):
    return r == a+b
def Mult(a,b,r):
    return r == a*b
def Sub(a,b,r):
    return r == a - b
def Div(a,b,r):
    return r == a / b

UserSelection =  {1 : Somar,2 : Sub,3 : Div,4 : Mult}
print("Calculadora 1.0")
print("1 - Somar\n\n2 - Subtração\n\n3 - Divisão\n\n4 - Multiplicação\n\n ")
Select = int(input())
a = int(input("Digite o 1° Número "))
b = int(input("Digite o 2° Número "))
r = 0
UserSelection[Select]()
print(r)

1 answer

2

There are several errors in your code, I can quote at first the fact that the return must receive only the value that must return.

What are you trying to do with the return r == a+b, for example, it is actually return if a + b is equal to r, that is, this statement returns a boolean value (Trueor False).

Then when we call the function on the line

UserSelection[Select]()

we should pass the arguments that are set as when we define the function up there. To do this, simply add the necessary values inside the parentheses and print on the screen the result of this function call (which is the value of the return).

This is the complete code:

def Somar(a,b): # Não é necessário o 'r', pois ele está preso no escopo da função
    return a+b # retorno o resultado da operação
def Mult(a,b):
    return a*b
def Sub(a,b):
    return a - b
def Div(a,b):
    return a / b

UserSelection =  {1 : Somar,2 : Sub,3 : Div,4 : Mult}
print("Calculadora 1.0")
print("1 - Somar\n\n2 - Subtração\n\n3 - Divisão\n\n4 - Multiplicação\n\n ")
Select = int(input())
a = int(input("Digite o 1° Número "))
b = int(input("Digite o 2° Número "))

r = UserSelection[Select](a, b) # Chamamos a função com os argumentos e atribuímos para r
print('A resposta é:', r) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.