0

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

1
  • As a technicality, your function still has a return statement, it's just implicit and it returns None. Try replacing tree(n) with res = tree(n); print(res) to see what I mean. Why can't you have an explicit return statement? Commented Mar 13, 2017 at 19:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's actually not a problem for a function to refer to a global variable that has not been defined yet. As long as the function is only called after the variable exists, it will work OK. That's not to say that passing the file as an argument would be bad though, it's just not strictly necessary. Your code above work, without any more rearranging.
@Blckknght thanks for that clarification. I must admit I didn't actually try it.

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.