Python Variables
In this page:
variable_name = value
variable_a, variable_b = value_a, value_b
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
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
value = 10 # value is currently an integer
print(value)
value = "ten" # same name reassigned to a string, no error
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
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
count = 0 # global variable
def increment():
global count # refer to the outer count instead of creating a local one
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
total_price = 49.99
print(total_price)
- Using a variable before assigning it, e.g.
print(total)beforetotal = 0, which raisesNameError. - Assigning to a variable inside a function and expecting the global one to change, when it just creates a new local variable.
- Writing
1st = 5ormy-var = 5as names; variable names cannot start with a digit or contain hyphens.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: