Variables

📦 Ready to store some data? Variables are your way of labeling information so you can use it later.

1 Assignment

Assign values to variables.

x = 10
y = 3.14
name = "Tyler"
is_active = True
nothing = None

print(x)  # 10
print(y)  # 3.14
print(name)  # Tyler
print(is_active)  # True
print(nothing)  # None
10
3.14
Tyler
True
None

2 Naming

  • Must start with a letter or underscore
  • Cannot start with a number
  • Can only contain alphanumeric characters and underscores
  • Are case-sensitive
value = 100
_value = 200
Value = 300

print(value)  # 100
print(_value)  # 200
print(Value)  # 300
100
200
300

3 Reassignment

Update a variable’s value.

counter = 1
print(counter)  # 1
counter = counter + 1
print(counter)  # 2
1
2
counter = 1
print(counter)  # 1
counter += 1
print(counter)  # 2
1
2

4 Multiple Assignment

Assign values to multiple variables in one line.

a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3
1 2 3
x = y = z = 0
print(x, y, z)  # 0 0 0
0 0 0

5 Dynamic Assignment

Variables can change type at runtime.

x = 5       # int
x = "five"  # now str
print(x)    # five
print(type(x))  # <class 'str'>
five
<class 'str'>

Best Practices

  • Use meaningful names (e.g., total_price instead of tp)
  • Stick to lowercase with underscores for readability (snake_case)
  • Avoid using Python keywords as variable names (e.g., class, list, print)
  • Use type() and print() to debug variable during development.

Common Errors

Some frequent errors encountered when dealing with Variables in Python.

1value = 10
  Cell In[8], line 1
    1value = 10
    ^
SyntaxError: invalid decimal literal
print(price)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 print(price)

NameError: name 'price' is not defined
def = 5
  Cell In[10], line 1
    def = 5
        ^
SyntaxError: invalid syntax
x, y = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 x, y = 1

TypeError: cannot unpack non-iterable int object