简体   繁体   中英

Calling a variable from another function

This is a simple example of the type of problem I have run into:

def making_list(text):
    list_ = []
    i = 0
    while i < int(len(text)):
        list_.append(text[i])
        i += 1
    return list_

def calling_list(list_):
    print list_

text = raw_input("text input")

making_list(text)
calling_list(list_)

The variable list_ , which comes from making_list , is not recognized by the function calling_list . What is a possible solution to this problem?

Thank you

You're not storing the variable anywhere.

mylist = making_list(text)
calling_list(mylist)

Explanation: The variable names are valid only in scope of the function. If you leave function (with returning some local variable), you are returning only the 'value' of the variable, not it's name, you need to assign it to variable outside.

You have to declare the variable that will take the output of making_list as its value. making_list function returns list_ ; but you can not reach it if you do not assign it to another variable out of your function.

list_ = making_list(text) will solve your problem.

Your making_list -function doesn't return anything. This will work

list = making_list(text)
calling_list(list)

That will work.

I don't want to change or optimize your code, I just want to give a possible solution:

1)If you want list_ to be stored in memory, change the last 2 lines of your code like this:

list_=making_list(text)
calling_list(list_)

Now you can access list_ anywhere in your code.

2)If you don't want to store list_ and you just want to print it and forget about it, delete the 2 last lines of your code and write this line instead:

calling_list(making_list(text))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM