I have a function that parses a file into a list. I'm trying to return that list so I can use it in other functions.
def splitNet(): network = [] for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines(): line = line.replace("\r\n", "") line = string.split(line, ',') line = map(int, line) network.append(line) return network
When I try to print the list outside of the function (for debugging) I get this error:
NameError: name 'network' is not defined
Is there something simple I am doing wrong or is there a better way to pass variables between functions without using globals?
A Python function can return any object such as a list. To return a list, first create the list object within the function body, assign it to a variable your_list , and return it to the caller of the function using the keyword operation “ return your_list “.
You simply pass a call to function generating your list as an argument (instead of global variable) to a call to function processing the list you want to generate.
Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.
Variables cannot be accessed outside the scope of a function they were defined in.
Simply do this:
network = splitNet() print network
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With