Working With Global Variables in Python Functions (Overview)

A global variable is a variable that you can use from any part of a program, including within functions. Using global variables inside your Python functions can be tricky. You’ll need to differentiate between accessing and changing the values of the target global variable if you want your code to work correctly.

Global variables can play a fundamental role in many software projects because they enable data sharing across an entire program. However, you should use them judiciously to avoid issues.

In this video course, you’ll:

  • Understand global variables and how they work in Python
  • Access global variables within your Python functions directly
  • Modify and create global variables within functions using the global keyword
  • Access, create, and modify global variables within your functions with the globals() function
  • Explore strategies to avoid using global variables in Python code
Download

Sample Code (.zip)

1.9 KB
Download

Course Slides (.pdf)

4.6 MB

00:00 Working with Global Variables in Python Functions

00:05 A global variable is a variable that you can use from any part of a program, including within functions.

00:12 Using global variables inside your Python functions can be tricky. You’ll need to differentiate between accessing and changing the values of the target global variable if you want your code to work correctly.

00:25 Global variables can play a fundamental role in many software projects because they enable data sharing across an entire program. However, you should use them judiciously to avoid issues. In this course, you’ll understand global variables and how they work in Python, access global variables within your Python functions directly, modify and create global variables within functions using the global keyword, access, create, and modify global variables within your functions with the globals() function, and explore strategies to avoid using global variables in Python code.

01:03 To follow along with this course, you should have a solid understanding of Python programming, including fundamental concepts such as variables, data types, scope, mutability, functions, and classes.

01:16 If you need to look any further into any of these areas, then Real Python has you covered, and you can use the search function on the site to access courses and tutorials on each of them.

01:27 Any code that you see running in the REPL will be using the bpython interpreter. This is a replacement Python interpreter that offers a number of enhancements, including code highlighting and suggestions.

01:38 But any code you see running on screen will work in the standard Python REPL, which is typically accessed by typing python or python3 at your terminal or command-line prompt.

01:50 So now you know what’s going to be covered. Let’s get started.

Become a Member to join the conversation.