Search code examples
pythonlistfunctionfor-loopnameerror

How to call the variable declared in user defined function in python


Whenever I define any function in python with variables, I am not able to call or print the values of variable declared in the function, and hence am unable to use that variable in subsequent lines of code. It'd be really helpful if I could know that where am I wrong in using it.

For example, the following lines of code of creating a list of 500 numbers: it gives error : NameError: name 'r1' is not defined

def createlist(r1):
    for n in range(1,500):
        return np.arange(r1, r1+n, 1)
    r1 = 1
    print(createlist(r1))

Solution

  • This code will not work for what you want.

    Instead try this code.

    import numpy as np
    def createlist(r1):
        for n in range(1,500):
            print(np.arange(r1, r1+n, 1))
    r1 = 1
    #print(createlist(r1))
    createlist(r1)