1

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))
2
  • This code is probably not what you're actually running - the function will return during the first iteration of the for loop and will never reach the final two lines, assuming you do call the function from somewhere. Commented Oct 7, 2020 at 4:32
  • Can you please help as in what should i do then? So that after all iterations then my function yields the last tow line outputs? Commented Oct 7, 2020 at 4:35

3 Answers 3

1

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)

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

Comments

1

The problem is because of indentation.

You are declaring r1 in your function. it gives you error because the print(createlist(r1)) can not see the r1. so the solution is :

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

Hope it helps you <3

Comments

1

I think you want to correctly indent your code and also you want to return the result of each iteration, you can try this

import numpy as np


def createlist(r1):
    op = []
    for n in range(1, 500):
        op.append(list(np.arange(r1, r1 + n, 1)))   # op is storing the list generated in each iteration
    return op   # now you can return op, a list which contains results from the loop


r1 = 1
print(createlist(r1))

p.s. Please include more explanation of what you want to do.

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.