Working With Global Variables in Python Functions (Summary)
You’ve learned that you can access global variables directly in your functions. However, to modify a global variable in a function, you must use either the global
keyword or the globals()
function.
Global variables allow you to share data across multiple functions, which can be useful in some situations. However, you should use this type of variable carefully and sparingly to avoid writing code that’s difficult to understand, debug, test, and maintain.
In this video course, you’ve learned how to:
- Work with global variables in Python
- Directly access global variables within your Python functions
- Modify and create global variables within functions using the
global
keyword - Access, create, and modify global variables within your functions with the
globals()
function - Use strategies to avoid using global variables in Python code
Now you know what it takes to correctly use global variables inside functions in Python, so you can use them effectively where appropriate. You also know that avoiding global variables is the best way to go most of the time. This will allow you to write more modular, maintainable, and reusable code.
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
Well done. You’ve made it to the end of the course. You’ve learned a lot about using global variables, particularly inside Python functions. You’ve learned that you can access global variables directly in your functions, but to modify a global variable in a function, you’ll need to use the global
keyword or the globals()
function. Global variables allow you to share data across multiple functions, which can be useful in some situations, but you should use this type of variable carefully and sparingly to avoid writing code that’s difficult to understand, debug, test, and maintain.
00:35
In this course, you’ve learned how to work with global variables in Python, directly access global variables within your Python functions, modify and create global variables within functions using the global
keyword, access create and modify global variables within functions using the globals()
function, and use strategies to avoid using global variables in Python code.
01:01 Now that you know what it takes to correctly use global variables inside functions in Python, you can use them effectively where appropriate. You also know that avoiding global variables is the best way to go most of the time. This will allow you to write more modular, maintainable, and reusable code.
01:19 We hope you found this course useful, and we’ll see you again soon at realpython.com.
Become a Member to join the conversation.