Python calculator does not return function

Asked

Viewed 297 times

1

I started using Python recently and am creating a calculator to train factors like function, input and function return within another function.

However, my calculator is not working, it simply does not return anything. It seems that it does not enter the if, even though the option is receiving the value.

Could help me identify the mistake?

def calculadora():    
    print("Ola! \n" "Bem vindo a calculadora digital em python! \n" "Por favor, digite a opcaoo:")
    print("Opcao 1: Soma \n Opcao 2: Subtracao \n Opcao 3: Multiplicacao \n Opcao 4: Divisao")
    opcao = input()
    if opcao == 1:
        print("Vamos somar!")
        return soma()
    elif opcao == 2:
        print("Vamos subtrair!")
        return subtracao()
    elif opcao == 3:
        print("Vamos Multiplicar!")
        return multiplicacao()
    elif opcao == 4:
        print("Vamos Dividir!")
        return divisao()
 

def multiplicacao():
    print("Agora, digite os valores a serem usados para a multiplicacao")
    n = input()
    m = input()
    return print("O resultado eh: ", n*m)

def soma():
    print("Agora, digite os valores a serem usados para a soma")
    n = input()
    m = input()
    return print("O resultado eh: ", n+m)

def subtracao():
    print("Agora, digite os valores a serem usados para a subtracao")
    n = input()
    m = input()
    return print("O resultado eh: ", n-m)

def divisao():
    print("Agora, digite os valores a serem usados para a divisao")
    n = input()
    m = input()
    return print("O resultado eh: ", n/m)


calculadora()
  • opcao = int(input())

  • As @Augustovasques said, put opcao = int(input()), for the input() returns a string, so you have to put the int() to convert the value to inteiro

  • If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

2 answers

2

input returns a string, but you’re comparing its return with an integer (on the line if opcao == 1). To make this comparison the right way you can turn the return into a number (using int(input(...)), as suggested by another answer), or compare it to a string: if opcao == '1'.

But I think there’s a better way. Note that there is a lot of repetition in the code: all operations ask you to enter the values, and the messages are practically the same, only changing the name of the operation. A better way would be to parameterize all this and also read the 2 values before each function.

Another detail is what you’re doing return print(...), only that print returns None and it makes no sense to return the result of a print (or you return the value, or print it). In the case of functions, I prefer that they return the value and who called them decide what to do with the return (and even print it).

Finally, a suggestion for improvement:

def calculadora(operacoes):
    print("Ola! \n" "Bem vindo a calculadora digital em python! \n" "Por favor, digite a opção:")
    print('\n'.join(f'Opção {i}: {op[0]}' for i, op in operacoes.items()))
    opcao = input()
    if opcao in operacoes:
        nome_operacao, verbo, funcao = operacoes[opcao]
        print(f'Vamos {verbo}!')
        print(f'Agora, digite os valores a serem usados para a {nome_operacao}')
        n = int(input())
        m = int(input())
        print(f'O resultado é {funcao(n, m)}')
    else:
        print('opção inválida')

def multiplicacao(n, m):
    return n * m

def soma(n, m):
    return n + m

def subtracao(n, m):
    return n - m

def divisao(n, m):
    return n / m

operacoes = {
    '1': ('soma', 'somar', soma),
    '2': ('subtração', 'subtrair', subtracao),
    '3': ('multiplicação', 'multiplicar', multiplicacao),
    '4': ('divisão', 'dividir', divisao)
}

calculadora(operacoes)

Now the function calculadora receives a dictionary containing the options and their operations (in fact, each option is mapped to a tuple containing the texts relating to the name of the operation and the function to be called).

Then I read the numbers and pass them as arguments of the function. Note that each function returns the result of the operation, and whoever called the function takes care of printing the final value (no return print, which, as I said, makes no sense).

This makes it more flexible (the function calculadora can receive a dictionary with completely different operations and still will work the same way) and avoids code repetitions (I no longer need to read the 2 numbers inside each function, as they only receive the values that have been read before - and also see that in this case I converted the values to int, otherwise you would be doing operations with strings). If you want, you can also use float instead of int, if the program accepts decimal numbers.

1

Exchange the input() for int(input()), for only the input(), returns a value like string, the int() will specify that the entree is whole, the code would look like this:

def calculadora():

    print("Ola! \n" "Bem vindo a calculadora digital em python! \n" "Por favor, digite a opcaoo:")
    print("Opcao 1: Soma \n Opcao 2: Subtracao \n Opcao 3: Multiplicacao \n Opcao 4: Divisao")
    opcao = int(input())
    if opcao == 1:
        print("Vamos somar!")
        return soma()
    elif opcao == 2:
        print("Vamos subtrair!")
        return subtracao()
    elif opcao == 3:
        print("Vamos Multiplicar!")
        return multiplicacao()
    elif opcao == 4:
        print("Vamos Dividir!")
        return divisao()
 

def multiplicacao():
    print("Agora, digite os valores a serem usados para a multiplicacao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n*m)

def soma():
    print("Agora, digite os valores a serem usados para a soma")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n+m)

def subtracao():
    print("Agora, digite os valores a serem usados para a subtracao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n-m)

def divisao():
    print("Agora, digite os valores a serem usados para a divisao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n/m)


calculadora()

Or you might rather compare with a number in function calculadora(), compare how string, and converting only into other functions, thus:

 def calculadora():

    print("Ola! \n" "Bem vindo a calculadora digital em python! \n" "Por favor, digite a opcaoo:")
    print("Opcao 1: Soma \n Opcao 2: Subtracao \n Opcao 3: Multiplicacao \n Opcao 4: Divisao")
    opcao = input()
    if opcao == '1':
        print("Vamos somar!")
        return soma()
    elif opcao == '2':
        print("Vamos subtrair!")
        return subtracao()
    elif opcao == '3':
        print("Vamos Multiplicar!")
        return multiplicacao()
    elif opcao == '4':
        print("Vamos Dividir!")
        return divisao()


def multiplicacao():
    print("Agora, digite os valores a serem usados para a multiplicacao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n*m)

def soma():
    print("Agora, digite os valores a serem usados para a soma")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n+m)

def subtracao():
    print("Agora, digite os valores a serem usados para a subtracao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n-m)

def divisao():
    print("Agora, digite os valores a serem usados para a divisao")
    n = int(input())
    m = int(input())
    return print("O resultado eh: ", n/m)


calculadora()
  • The fact that it has dynamic typing has nothing to do with the fact that input return string, are distinct characteristics that do not interfere with each other: https://answall.com/q/21508/112052

  • thanks, I will edit

Browser other questions tagged

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