Using Name Of Strings In Different Functions
I need to use movies_list from the first function in the second. How do I do that? def movie(): movies_list = [movie.strip() for movie in movies_list] movie_explorer() def
Solution 1:
The Good
Use return
and arguments
def movie():
movies_list = [movie.strip() for movie in movies_list]
movie_explorer()
return movies_list
def rand(movies_list):
rand_item = print(random.choice(movies_list))
And when calling rand
remember to call the function as
rand(movie())
The Bad
Add a line
global movies_list
as the first line in both functions
And the Ugly
You can make use of the globals
object available. (Adding it here to complete the rhyme)
def movie():
global movie_returns
movie_returns = [movie.strip() for movie in movies_list]
movie_explorer()
# No return
def rand(): # No argument
movies_list = next((globals()[v] for v in globals() if v=='movies_return'))
rand_item = random.choice(movies_list)
Solution 2:
Make the second function nested on the first one, here you have an example:
def hello():
a = "hello"
def world():
return "%s world" % a
return world()
print hello()
Solution 3:
put the two functions in a class, and make movies_list a class variable.
Post a Comment for "Using Name Of Strings In Different Functions"