Variables & Data Lesson 5 of 23
Python Variables
Create variables in Python, follow naming rules, change values, assign several variables at once, and swap values in one line.
A variable is a name that refers to a value stored in the computer's memory. Python makes variables very easy: no special keyword, no type declaration. Just a name, an equals sign, and a value.
Creating variables
student = "Maria Clara"
grade_level = 10
average = 94.5
is_officer = True
print(student, grade_level, average, is_officer)
Output
Maria Clara 10 94.5 True
The variable is created the moment you first assign a value to it. Python figures out the type (text, number, and so on) by itself.
Changing values
baon = 150
print("Start:", baon)
baon = baon - 45 # lunch
baon -= 20 # fare (shortcut for baon = baon - 20)
print("Left:", baon)
Output
Start: 150 Left: 85
The = means "store", not "equals". baon = baon - 45 takes the current value, subtracts 45, and stores the result back.
Shortcut operators
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
Naming rules
- Names can contain letters, digits and underscores
_. - They can't start with a digit:
1st_placeis invalid,first_placeis fine. - No spaces or dashes:
final gradeandfinal-gradeare invalid. - They're case-sensitive:
Ageandageare different. - You can't use Python keywords like
if,for,class,Trueordef.
By convention, Python uses snake_case: lowercase words joined with underscores, like total_price and student_count.
Several variables at once
math, science, english = 88, 91, 85
print(math, science, english)
x = y = z = 0 # all three start at 0
print(x, y, z)
Output
88 91 85 0 0 0
Swapping two values
In many languages, swapping needs a temporary variable. Python does it in one line:
first = "Ana"
second = "Ben"
first, second = second, first
print(first, second)
Output
Ben Ana
Constants
Python has no true constants, but programmers write names in ALL_CAPS to mean "please don't change this":
PASSING_GRADE = 75
VAT_RATE = 0.12
SCHOOL_NAME = "Rizal National High School"
Using a variable before creating it
print(score)
Error
NameError: name 'score' is not defined
A variable must be assigned before it's used. This error also appears when you misspell a name, like scroe instead of score.
Variables are labels
A helpful way to picture Python variables: they're name tags stuck on values, not boxes. a = b doesn't copy the value; it puts a second tag on the same value. For numbers and text this doesn't matter, but for lists it does, as you'll see in the Lists lesson.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04