how do i get data from one function to another?

Ive just made few changes here, and run it and got no errors because I dont know what to type in order to get the right results. Anyways all the changes are related to global and redefinition of values.

# say these outside all the functions, in the main block
words_correct = 0
words_wrong = 0 
vocabulary = ['kip', 'hok', 'bal', 'muis', 'gat'] 
words_passed = [] 

def dictee():
    global word, answer
..... #same bunch of codes
def check():
    global answer, words_correct, words_wrong
.... #same bunch of codes

Why do we have to say global? Basically because when we define variables they either get defined on local scope or global scope, variables defined on main block(outside of all function) are on global scope, while inside functions are on local scope. Variables defined on global scope can be accessed anywhere and that on local can only be accessed from within where its defined.

Where do we have to use global? We say global where we define the variable or we redefine, or at least this is what I know of. We need to say global where we declare the variable, like, a = 'good', we also need to say global if we are changing it, a = 'bad' or a += 'day' because we are assigning a new value to it. Using global outside of all functions, on the main block, is useless.

Why are we declaring words_correct and words_wrong outside all functions? It is simply because if you declare and set its value to 0 inside dictee(), each time the function is run the value of those variables will change to 0, which means score will always be 0 or 1, so we define it once only, in the main block. Same logic applies to the two lists(vocabulary and words_passed), each time function runs they reset the list to the full list of words, so to get rid of that, just define it once in the main block.

I also think using parameters here might need re-structuring of your code as your calling both function from each other.

Note that we only say global on functions, out side functions all defined variables are open to global scope and can be accessed from anywhere in the code.

PS: This is just my understanding of global over the span of 4 months, do correct me if im wrong anywhere, thanks 😀

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top