Cactuses
Cactuses

Reputation: 79

Why can't I print a returned value?

I've written this code, and I want to be able to use the dictionary I created in the function as an argument for another function but I can't seem to print it on it's own, or use it as an argument as 'names is not defined'. How do I create the same output (a list of dictionaries with dictionaries as values) but also being able to use the dictionary outside of the function?

def get_name(string_input):
    l = [line.split('is connected to') for i, line in enumerate(string_input.split('.')) if i % 2 == 0]
    names = {name[0]:{} for name in l}
    return names

print get_name(example_input) 
print names

Upvotes: 1

Views: 621

Answers (2)

apxp
apxp

Reputation: 5894

You are messing up with the variable scope of python.

A variable always has a scope where it is valid. Local variables which are declared inside a function are just valid inside that function.

In that example a is defined outside. Inside myFunc() there is also an a variable which has no reference to the a variable from outside. That means inside your computer memory a (outside) has a different part of the memory than a (inside myFunc).

a = "A String"
def myFunc(str):
    a = str
    return a

print myFunc("Hello World!") // Hello World!
print a // A String

A little bit more information about variable scopes in python:

Short Description of the Scoping Rules?

Upvotes: 0

k4ppa
k4ppa

Reputation: 4667

You must assign the returned value

names = get_name(example_input) 
print names

The variable names used inside the function is local, so not visible outside.

Upvotes: 3

Related Questions