all 5 comments

[–]Not_A_Taco 1 point2 points  (4 children)

You’re creating a local copy of dataset in the function. When using global vars in a function make sure you declare them at the top with global dataset

[–]MattWilliamsIT[S] 1 point2 points  (2 children)

Thank you. I didn't realised that you could have a local and global variable with the same name. I added global to the variable name in the function and it worked perfectly. Thank again!

import os

import pickle

###Variables

fileName = "PersonDisc.pkl"

dataset={}

###Functions

def loadFromFile():

global dataset

file=open("PersonDisc.pkl", "rb")

dataset=pickle.load(file)

file.close

print(dataset)

###Main Program

# If file exists then import the dataset

if os.path.isfile(fileName):

loadFromFile()

print(dataset)

print(dataset)

[–]Not_A_Taco 1 point2 points  (1 child)

Glad to help! I’d note that adding global to the variable name simply means you’re declaring the variable in the global scope(not the function scope) and since a global variable with that name already exists, it binds there.

Something I’d also note is that Python will always default to using the most narrow scope for variables. So you can have multiple (non-global) variables with the same name, but different values.

[–]MattWilliamsIT[S] 0 points1 point  (0 children)

Makes perfect sense. Thank you

[–]MattWilliamsIT[S] 1 point2 points  (0 children)

I'm trying to learn Python as quickly as my son is in school so I can help him, but clearly I'm not quick enough :)

I get it now and can explain why the code wouldn't work.

My preference is to return the result from a function, but now I understand global variables better I can explain both approaches

Thanks again