Search⌘ K
AI Features

Unbound Variables

Explore how Python manages variables that have not been assigned values. Understand what unbound variables are and learn why referencing them causes a NameError. This lesson helps you grasp Python's error handling to write safer and more reliable code.

We'll cover the following...

Take another look at this line of code from the approximate_size() function:

Python 3.5
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000

You never declare the variable multiple, you just assign a value to it. That’s OK, because Python lets you do that. What Python will not let you do is reference a variable that has never been assigned a value. Trying to do so will raise a NameError exception.

Python 3.5
x
#Traceback (most recent call last):
# File "/usercode/__ed_file.py", line 1, in <module>
# x
#NameError: name 'x' is not defined
Python 3.5
x = 1
print (x)
#1

You will thank Python for this one day.