Skip to content

Joseph-T-Gordon

A complete log of all recent projects and skills

Menu
  • About me
  • Posts/Projects
  • Resume/Certifications
Menu

Post #44 (Python Programming) – Global variables

Posted on April 26, 2023June 26, 2023 by admin

Within python’s functions any variables defined inside the function can only be used within that function, the function can use variables defined outside of it.

Code:

a = 3

def function():

print(a)

function()

Result:

3

Here is an example of how the variable within the function cannot influence the outside variable, it’s as if they are two separate values.

Code:

a = 1

def function():

a = 2

print(a)

function()

print(a)

Result:

2

1

You’d expected both to print 2 as the result however the a in the function and the a defined outside of it are two different variables essentially. So what if you wanted to use one variable that is updated inside or outside of function, this is where global variables come in and allow me to end this post with an example.

Code:

a = 1

def function():

global a

a = 2

print(a)

function()

print(a)

Result:

2

2

As you can see both return 2, that is because now when we set the variable to 2 within that function it has an effect outside the function as well, as always feel free to reach out with any questions.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

© 2025 Joseph-T-Gordon | Powered by Minimalist Blog WordPress Theme