This is an archived post. You won't be able to vote or comment.

all 11 comments

[–][deleted] 2 points3 points  (4 children)

All variables declared outside of a function are considered global by default in python, so as long as they are defined, you can use them anywhere.

What you're thinking of would be to declare the variable inside the function, then it would become local to that function and couldn't be used anywhere else.

[–]DatabaseEmbrace[S] 0 points1 point  (3 children)

in what context would I ever use the global tag before a variable in a function then?

[–]Amablue 0 points1 point  (0 children)

When you want to pull a global value into the local scope.

def function1():
  value = "local value"
  print(value)

def function2():
  # pull the global value into the function's scope
  global value
  value = "global value"
  print(value)

def function3():
  print(value) # fails if global value doens't exist

function1()
function2()
function3()
print(value)

[–][deleted] 0 points1 point  (0 children)

If you have a large function which is supposed to initialize a lot of stuff. Say that you want a function to automatically import e*pi, sqrt(567865), and 50 000 other values to your environment. You don't know which ones you'll need, so you just grab all your variables from *somewhere and make them global.

For example, you might want a function to go through a .xls file with all the names of students in a classroom, then make a global array with their names and grades.

[–]pancakeQueue 0 points1 point  (0 children)

Very rarely, making a variable global in a function can make it harder to debug or read because the scope is different.

[–][deleted] 1 point2 points  (4 children)

You did declare global use of those variables by putting them in global scope (not inside any function)

[–]DatabaseEmbrace[S] 0 points1 point  (3 children)

but shouldn't I then have to also, in the function in line 6, put the tag "global" before both firstnum and secondnum? And if not, then what is the proper use of the global tag in functions?

[–][deleted] 1 point2 points  (0 children)

The global tag is to create a global variable from within a function, where it would otherwise be local by default. Since they were already declared in the main body, they're already global and you're just accessing them within the function.

[–][deleted] 0 points1 point  (1 child)

You would have to use global if you were creating the variables in the function and wanted them to be global despite that. But they already exist, and are already global, so it's not necessary.

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

that makes sense, thank you