← Back to Python Course | Chapter 1: Basics | Lesson 9 of 14

Python Variables

Variable Assignment

Unlike statically-typed languages, Python needs no separate declaration step — writing age = 25 both creates the variable age and assigns it a value in one line, and the interpreter figures out its type from the value itself.

Example: Variable Assignment

python
age = 25
print(age)

Dynamic Typing in Variables

Because Python variables aren't bound to a fixed type, the same name can hold an integer on one line and a string a few lines later with no special syntax — the variable simply now refers to whatever the newest assignment set it to.

Example: Dynamic Typing in Variables

python
value = 10
print(value)
value = "ten"
print(value)

Multiple Variables

Writing a, b, c = 1, 2, 3 assigns all three variables in a single statement, which is a common, readable way to initialize several related values at once instead of three separate assignment lines.

Example: Multiple Variables

python
a, b, c = 1, 2, 3
print(a, b, c)

Local vs. Global Variables

A variable created inside a function only exists within that function's local scope and disappears once the function returns; variables created outside any function are global and visible everywhere. Using the global keyword inside a function lets you reassign that outer variable rather than accidentally creating a new local one.

Example: Local vs. Global Variables

python
count = 0

def increment():
    global count
    count += 1

increment()
print(count)

Best Practices for Variables

Favor full, descriptive names (total_price rather than tp) so a reader can understand a variable's purpose without having to trace back to where it was first assigned — this pays off enormously once a script grows past a few dozen lines.

Example: Best Practices for Variables

python
total_price = 49.99
print(total_price)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.