0

Why is x not defined outside the function? Is return x placed wrong?

def find(): 

x else:

find()
4
  • 6
    You are breaking before you are returning, and should your conditional statement evaluate to false you aren't returning at all. Commented Apr 23, 2015 at 14:25
  • 1
    break immediately exits the loop, so the statement after it is never executed. Commented Apr 23, 2015 at 14:25
  • please review stackoverflow.com/questions/291978/… Commented Apr 23, 2015 at 14:26
  • If you don't explicitly return, Python returns None Commented Apr 23, 2015 at 14:27

2 Answers 2

6

Put return x outside the loop:

def find(): 
    data=file('file.dat')
    x=0
    for line in data:
        if 'metaend' in line:
            break
        else:
            x+=1
    return x

To get the value of x, you use the return value of the function:

count = find()
Sign up to request clarification or add additional context in comments.

Comments

2

Your function never returns anything. Check this, with some added error handling for no end of metadata detection

def find(): 
    data=file('file.dat')
    x=0
    for line in data:
        if 'metaend' in line:
            return x

        x += 1
    raise Exception('heeey no end of metadata')

By the way, python has a very nice function for a counter in a loop:

def find(): 
    data=file('file.dat')

    for counter, line in enumerate(data):
        if 'metaend' in line:
            return counter

    raise Exception('heeey no end of metadata')

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.