0

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

def find(): 

x else:

find()
pythonman11
  • 1
  • 1
  • 5

2 Answers2

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()
Barmar
  • 741,623
  • 53
  • 500
  • 612
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')
hitzg
  • 12,133
  • 52
  • 54
bgusach
  • 14,527
  • 14
  • 51
  • 68