You are getting this error because of scoping issue. Basically you have defined variable in the local outer scope and are referencing it in method named foo. Do it like this. It will work fine:
x = 10
def bar():
print(x)
If you want to get a deeper understanding of python you can watch this youtube video: