41

If I have this:

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])

def anotherFunction():
    for letter in word:              #problem is here
        print("_",end=" ")

I have previously defined lists, so oneFunction(lists) works perfectly.

My problem is calling word in line 6. I have tried to define word outside the first function with the same word=random.choice(lists[category]) definition, but that makes word always the same, even if I call oneFunction(lists).

I want to have a different word every time I call the first function and then the second.

Can I do this without defining that word outside the oneFunction(lists)?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
JNat
  • 1,456
  • 4
  • 34
  • 37
  • 2
    Why not pass `word` as an argument to `anotherFunction`? Consider `def anotherFunction(word):` and calling it accordingly. – Lev Levitsky Apr 13 '12 at 11:24

8 Answers8

82

One approach would be to make oneFunction return the word so that you can use oneFunction instead of word in anotherFunction :

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    return random.choice(lists[category])

    
def anotherFunction():
    for letter in oneFunction(lists):              
        print("_", end=" ")

Another approach is making anotherFunction accept word as a parameter which you can pass from the result of calling oneFunction:

def anotherFunction(words):
    for letter in words:              
        print("_", end=" ")
anotherFunction(oneFunction(lists))

And finally, you could define both of your functions in a class, and make word a member:

class Spam:
    def oneFunction(self, lists):
        category=random.choice(list(lists.keys()))
        self.word=random.choice(lists[category])

    def anotherFunction(self):
        for letter in self.word:              
            print("_", end=" ")

Once you make a class, you have to instantiate an instance and access the member functions:

s = Spam()
s.oneFunction(lists)
s.anotherFunction()
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • thank you! In the first approach, can you please explain me exactly what the `self` part does? Is it an argument for the function? – JNat Apr 13 '12 at 11:32
  • @JNat: `self` gives you the reference to the current object, much like what `this` (pointer) or `this` (variable) serves in notable OOP Languages. – Abhijit Apr 13 '12 at 11:34
  • python tells me `self` is not defined... why is that? do I need to import some module before or something? – JNat Apr 13 '12 at 11:45
  • @JNat: You have to make a class, the same way I showed in the example. I think you are not comfortable with OO so I will update my answer to add more details. – Abhijit Apr 13 '12 at 11:46
  • I did define a class with the two functions inside of it, but when call the first function (`Spam.oneFunction(self,lists)`) he tells me `self` is not defined... – JNat Apr 13 '12 at 11:48
  • that final addition you made is supposed to be written outside the class definition right? – JNat Apr 13 '12 at 11:51
  • @JNat: Yes, Just define the class, and then the next three statements place is somewhere outside your class. – Abhijit Apr 13 '12 at 11:53
  • Python tells me (after I added those three statements) that global name word is not defined... WHY? – JNat Apr 13 '12 at 12:22
  • @JNat: Did you use it as it is. Did you prefix self, before every occurrence of word? – Abhijit Apr 13 '12 at 12:25
  • I missed the `self` in one `word`... that was it. Can you explain to me why I need those last three statements? – JNat Apr 13 '12 at 12:29
  • @JNat: Its difficult to describe in few lines. I would suggest either you read about [Classes](http://docs.python.org/tutorial/classes.html) are raise a separate question. – Abhijit Apr 13 '12 at 12:32
  • the two statements: `s.oneFunction(lists) s.anotherFunction()` execute the functions. So they really are not needed in order to define the class. Is that it? – JNat Apr 13 '12 at 12:56
33

Everything in python is considered as object so functions are also objects. So you can use this method as well.

def fun1():
    fun1.var = 100
    print(fun1.var)

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)
Python Learner
  • 477
  • 6
  • 15
  • 1
    This approach is an abuse of function attributes, and future calls will overwrite the value from previous calls. – SuperStormer Feb 15 '22 at 21:10
  • I really like this approach. For the purpose of inspecting variables inside functions in unit tests, I think this is a great approach. – Gabriel Staples May 12 '23 at 05:16
9

The simplest option is to use a global variable. Then create a function that gets the current word.

Notice that to read global variables inside a function, you do not need to use the global keyword. However, to write to a global variable within a function, you do have to use the global keyword in front of the variable declaration within the function, or else the function will consider it a separate, local variable, and not update the global variable when you write to it.

current_word = ''
def oneFunction(lists):
    global current_word
    word=random.choice(lists[category])
    current_word = word
    
def anotherFunction():
    for letter in get_word():              
          print("_",end=" ")

 def get_word():
      return current_word

The advantage of this is that maybe your functions are in different modules and need to access the variable.

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
0n10n_
  • 382
  • 3
  • 10
4
def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    word = random.choice(lists[category])
    return anotherFunction(word)
Allan Mwesigwa
  • 1,210
  • 14
  • 13
  • You can pass the word variable from the first function 'oneFunction' to the other function. However, I guess you have to put the other function first less you get an error, "anotherFunction is not defined". Also, I noticed, you are not doing anything with the 'letter' variable that you have referenced in the for-loop – Allan Mwesigwa Jan 10 '17 at 09:14
1

so i went ahead and tried to do what came to my head You could easily make the first function to return the word then use the function in the another function while passing in an the same object in the new function like so:

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction(sameList):
    for letter in oneFunction(sameList):             
        print(letter)
  • Hey! This _should_ work — something similar was suggested in [the accepted answer](https://stackoverflow.com/a/10139935/1328704) :) – JNat Jun 17 '21 at 20:01
0
def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction():
    for letter in word:             
        print("_",end=" ")
Deepak Kabbur
  • 774
  • 14
  • 25
0
def abc():
    global x
    x = 4 +5 
    return x

def klm():
    y = x + 5
    print(y)

When we want to use a function variable into another function , we can simply use 'global' keyword. Note: This is just a simple usage, but if you want to use it within a class environment, then you can refer above answers.

0

Solution 1:

Either define variable as global, then print the variable value from the second script. Ex:

python_file1.py
x = 20

def test():
  global x
  return x
test()

python_file2.py
from python_file1 import *
print(x)

Solution 2:

This solution can be useful when the variable in function 1 is not predefined. In this case need to store the output of first python file in a new variable in second python file. Ex:

python_file1.py
def add(x,y):
    return x + y


if __name__ =="__main__"
add(x=int(input("Enter x"),y = int(input("Enter y"))

python_file2.py
from python_file1 import * 
# Assign functions of python file 1 in a variable of 2nd python file
add_file2 = add(5,6)

def add2()
  print(add_file2)

add2()
JNat
  • 1,456
  • 4
  • 34
  • 37
Prosenjit Bari
  • 117
  • 1
  • 2