0

I made a function that is being called recursively, and the condition for it to keep being called is a user input.

The recursion is working but the final value of the variable is being returned as None. I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, etc.

Here is my code:

Main Py:

import funcoes_moeda

def switch(valor):
    case = int(input('Escolha uma opcao... (0 para encerrar) : '))
    if case == 1:
        valor = funcoes_moeda.aumentar(valor)
        print('Valor aumentado: {}'.format(valor))
        switch(valor)

    elif case == 2:
        pass
    elif case == 3:
        pass
    elif case == 4:
        pass
    else:
        return valor

valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
    "1 - Aumentar Valor \n" \
    "2 - Diminuir Valor \n" \
    "3 - Dobrar Valor \n" \
    "4 - Dividir Valor \n" \
    "0 - Encerrar o Prorama"
    )

valor = switch(valor)

print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))

Imported Functions:

def aumentar(valor):
    quantia_aumentada = float(input('Insira a quantidade que voce deseja acrescentar: '))
    valor += quantia_aumentada
    return valor

def diminuir():
    pass

def dobro():
    pass

def metade():
    pass

When i tried executing this, what i got was:

Insira o valor: 100.00

Escolha a funcao a ser aplicada no valor inserido:

1 - Aumentar Valor

2 - Diminuir Valor

3 - Dobrar Valor

4 - Dividir Valor

0 - Encerrar o Prorama

Escolha uma opcao... (0 para encerrar) : 1

Insira a quantidade que voce deseja acrescentar: 100.00

Valor aumentado: 200.0

Escolha uma opcao... (0 para encerrar) : 1

Insira a quantidade que voce deseja acrescentar: 100.00

Valor aumentado: 300.0

Escolha uma opcao... (0 para encerrar) : 0

Funcao foi aplicada. O valor final ficou: None

For a test case, you can use:

Chose 100.00, option 1 (2 times is enough), increment 100.00 each call. Expected output: Current value = 300.00 (Because 100 + 100 + 100)

But i got None at the last print...

Please. What am i doing wrong??? :( Thank you for all the help.

PS: I tried going through the following answers, but i was not able to solve this problem because the explanation was for the problems in the question, and i found it was a litle different than mine..

1 > Recursive function returning none - Dint understand.

2 > python recursive function returning none instead of string - This is treating a CSV file.

2
  • if case == 2 the function falls off the end and returns None. Also, if you want a recursive function to return something you better return the recursive call (return switch(...)). Commented Dec 3, 2022 at 23:23
  • Indeed: you should implement a return valor (or other return... statement) in ALL cases. Commented Dec 3, 2022 at 23:26

3 Answers 3

1

The problem is that when the case variable is equal to 0, the return valor statement is being executed within the switch() function, but this function is being called recursively so the value of valor is not being returned to the caller.

To fix this, you can add another return statement at the end of the switch() function that returns the value of valor when case is 0. This will ensure that the value of valor is returned to the caller, even when the switch() function is being called recursively.

def switch(valor):
    case = int(input('Escolha uma opcao... (0 para encerrar) : '))
    if case == 1:
        valor = funcoes_moeda.aumentar(valor)
        print('Valor aumentado: {}'.format(valor))
        switch(valor)

    elif case == 2:
        pass
    elif case == 3:
        pass
    elif case == 4:
        pass
    else:
        return valor

    # Return the value of valor when case is 0
    return valor
Sign up to request clarification or add additional context in comments.

4 Comments

Note with this fix, the else: statement becomes superfluous. But, for it to work, you'd need to write valor = switch(valor) in line 6.
Hey @Swifty ! What do u mean by superfluous? Can u explain it a little better? Like... Can i remove this else statement, then ? (What i want to achieve with this else: If user inputs something other than 1, 2, 3 and 4, program will stop.)
I mean that, if you add a final return valor statement, it will be executed at the end of the script, so the else: ... isn't useful any more.
Thank you guys! I was able to solve the issue and removed the superfluous else. It worked...
0

When returning a value the recursion is braking and the value returns to the previous call of the function. If you want to return the value to the first call, you can return the value every time you call switch:

import funcoes_moeda

def switch(valor):
    case = int(input('Escolha uma opcao... (0 para encerrar) : '))
    if case == 1:
        valor = funcoes_moeda.aumentar(valor)
        print('Valor aumentado: {}'.format(valor))
        return switch(valor)

    elif case == 2:
        pass
    elif case == 3:
        pass
    elif case == 4:
        pass
    else:
        return valor

valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
    "1 - Aumentar Valor \n" \
    "2 - Diminuir Valor \n" \
    "3 - Dobrar Valor \n" \
    "4 - Dividir Valor \n" \
    "0 - Encerrar o Prorama"
    )

valor = switch(valor)

print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))

2 Comments

This still won't work if at any time you choose options 2-4; you should replace pass with return valor (as placeholders until these cases are treated) or add a final return valor, or simply remove else: and unindent return valor.
No worries. The only case im using atm is Case 1. I will replicate it to others when i understand it fully.
0

Two issues:

  1. The return at the end of the function 'switch' should be at the end of the function and not part of the 'else' case. Because if you select '1' you will change the value of 'valor', but after changing the value you exit the function withou returning a value.
  2. The returned value of the recursive call to 'switch' in the code section of 'if case == 1:' is not saved and therefore lost.

If you only correct the first point above you will get changed values only from the top call to 'switch', but all changes from the recursive calls will get lost.

The solution proposed by thebjorn solves both above listed issues. But treating the issues one by one, might be easier to understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.