Skip to content
dreamcode
dreamcode
Map
Variable scope
Lesson 24 of 77
+15 XP on finish
PYTHON BASICSChapter 4 · Functions

Local and global variables

Variables created inside a function are local to that function. They cannot be seen or used outside. Variables created outside functions are global and can be read anywhere.

Worked example

How it reads

  • sky = "neon" is a global variable accessible inside and outside paint()
  • cloud = "puffy" is a local variable only accessible inside paint()
Cloud tip: Keeping variables local helps prevent errors, because different functions won't accidentally overwrite each other's data.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add a global visits = 0 and a function visit() that uses global visits to add 1. Call it twice, then print visits: 2.

Press Run to check your work.