scooter800m
scooter800m

Reputation: 3

Python Recursive (extended)

i have looked for a solution to this but can't find one. i want to do a recursion but the function cannot have a return statement. here is the program:

n = input("Input a positive integer: ")

text = open("Nummbers.txt", "w")
text.write("Number inputed: " + str(n))
tree(n)

def tree(n):
    if(n>0):
        tree(n-1)
        print(n)
        text.write(str(n))
        tree(n-1)

when i run it it gives me a 'tree not defined error'. tree must be written as above. how do i get this to work properly all recursion tutorials that i have seen have set it up as such, i am using python 2.7

Upvotes: 0

Views: 52

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308130

Your def tree(n): must come before the first call to it in the main body of the code. Just rearrange:

def tree(n):
    if(n>0):
        tree(n-1)
        print(n)
        text.write(str(n))
        tree(n-1)

n = input("Input a positive integer: ")

text = open("Nummbers.txt", "w")
text.write("Number inputed: " + str(n))
tree(n)

Of course you now have the opposite problem, text is not defined inside the function. You should add that as a parameter as well, or you could rearrange again and split the code up.

Upvotes: 1

Related Questions