Code has been added to clipboard!

Python Global Variables: How Do They Differ From the Local Ones?

Reading time 2 min
Published Feb 13, 2020
Updated Feb 13, 2020

TL;DR – Python global variables are declared outside a function and can be accessed anywhere in the code.

The difference between local and global variables in Python

In the example below, you can see two variables declared – bit and bdg:

Example
def f():
    bit = "BitDegree"
    print (bit)
f()

bdg = "BitDegree"
print (bdg)

While both have the same value assigned, they are declared and used differently:

  • bit is declared within the function. This makes it a local variable. Its scope is the body of the function – it cannot be used anywhere else.
  • bdg is declared outside of the function – this makes it global. You can use Python global variables anywhere in the code.
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid certificates of completion
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

How to use global variables in Python

When declaring global variables in Python, you can use the same names you have already used for local variables in the same code – this will not cause any issues because of the scope difference:

  • If you use the variable within the function, it will prefer the local variable by default:
  • Example
    pizza = "Pepperoni"
    def f():
        pizza = "Hawaii"
        print (pizza)
    
    f()
  • If you use the variable anywhere else in the code, you will get the value of the global variable:
  • Example
    pizza = "Pepperoni"
    def f():
        pizza = "Hawaii"
    
    print (pizza)

You can also create local variables by modifying previously defined Python global variables inside the function by using the keyword global:

Example
bdg = 1000

def f():
    global bdg
    bdg = bdg + 500

Python global variables: useful tips

  • You can change the value of a Python global variable by simply assigning it a new value (redeclaring).
  • To delete a variable, use the keyword del. Trying to use a deleted variable will cause an error to fire.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 18/01/2021
3176 People Used
Only 97 Left
Rating
5.0