Python Crash Course
)}

Scope

Functions are re-usable sections of code that can accomplish a specific task. Every variable declared inside a function is limited to the function scope.

Scope is a region of the program where a defined variable can have its existence, beyond which the variable cannot be accessed.

In this article, you will learn about function scope by trying to access variables inside, and outside of it.

Function scope

Declare a random function that initializes a string variable.

def random_function(): name = 'Bill'

The name variable was declared inside the function scope (in other words, within the indented region). Try to access the variable outside the scope.

def random_function(): name = 'Bill' print(name)

>>NameError: name 'name' is not defined

You are left with an error because name was declared inside of the function scope, and does not exist outside of it. As such, print(name) must be indented into the scope.

def random_function(): name = 'Bill' print(name)
random_function()

>>Bill

T‍hat's all!

Scope is simply a reminder of always checking your indentation and that your variables are placed exactly where they need to be.

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.