iAeE8364.ZG8364
iAeE8364.ZG8364

Reputation: 3

Why is this recursion function not working?

Here is my code:

#recursion function
var = 0
def recursion_function(n):
    if(n > 0):
        var + 1
        print(str(var))
        recursion_function(n-1)
recursion_function(6)

And here is the output:

0  
0  
0  
0  
0  
0  

Process finished with exit code 0

How do I make the output like this:

1  
2  
3  
4  
5  
6  

Please help, because I can't find the recursion error...

Upvotes: 0

Views: 46

Answers (2)

Deepender
Deepender

Reputation: 67

 var + 1
    ^
    |

In your recursion_function you are not assigning var ! Also and your recursion_function does not know what this var is

Good way to write code

var = 6
def recursion_function(n):
    if(n > 0):
        print(str((var + 1)-n))
        recursion_function(n-1)
recursion_function(var)

Your Desired Output:

1
2
3
4
5
6

Upvotes: 0

Primusa
Primusa

Reputation: 13498

You are not actually changing the value of var. Replace var + 1 with var +=1.

var = 0
def recursion_function(n):
    global var
    if(n > 0):
        var += 1
        print(var)
        recursion_function(n-1)
recursion_function(6)
>>>1
>>>2
>>>3
>>>4
>>>5
>>>6

Upvotes: 1

Related Questions