Mounarajan
Mounarajan

Reputation: 1427

can't return a variable outside the function

I am trying to return the output from a function and trying to do a function call in afor loop and printing the output in same loop. But it is not working:

pagination_urls = ["http://google.com"]

def oss(url):
    data = url
    return data


for url in pagination_urls:
    oss(url)
    spider = data
    print spider

Output:

Traceback (most recent call last):
  File "mongo.py", line 10, in <module>
    spider = data
NameError: name 'data' is not defined

How to make this program work?

Upvotes: 0

Views: 1491

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1123042

Local variables in one function do not magically appear outside of that function. return returns the value, not the name of the variable. Instead, explicitly assign the return value:

for url in pagination_urls:
    spider = oss(url)
    print spider

Here the return value of oss() (whatever object the return statement produced in oss) is assigned to the spider variable.

Upvotes: 0

Stefan
Stefan

Reputation: 2194

You are not assigning the output of oss() to any variable. Try this:

pagination_urls = ["http://google.com"]

def oss(url):
    data = url
    return data


for url in pagination_urls:
    data = oss(url)
    spider = data
    print spider

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117946

You need to use the returned value

for url in pagination_urls:
    spider = oss(url)
    print spider

This will take the returned value data from the oss function, and assign it to your spider variable

Upvotes: 1

Related Questions