Reading — step 1 of 8
Learn
Imagine you're moving into a new apartment. You have boxes everywhere — one labeled "kitchen stuff," another labeled "winter clothes," another labeled "important documents." Variables are your program's labeled boxes. They let you store a value, give it a name, and use that name to reach the value whenever you need it.
Creating a variable
In Python, you create a variable by assigning a value to a name with =:
That single equals sign is called the assignment operator. Read it left-to-right as "the name on the left now refers to the value on the right." From that line onward, anywhere you write name, Python substitutes "Alice". Anywhere you write age, Python substitutes 25.
Unlike many languages, you don't declare the type of a variable. Python figures it out from whatever you assigned. This is called dynamic typing.
The four types you'll use every day
Python has many built-in types, but four cover 90% of beginner code:
A fifth special value, None, represents "no value yet" — useful as a placeholder.
Use type() to ask Python what type a value is:
Reassignment
A variable doesn't lock to its first value. You can reassign:
The variable always reflects its most recent assignment. The old value is forgotten.
Naming rules
Python is strict about what's a valid variable name:
- ✓ Letters, digits, underscores. Case sensitive:
Ageandageare different variables. - ✓ Must start with a letter or underscore —
name,_name,name1are fine. - ✗ Cannot start with a digit:
1nameis a syntax error. - ✗ Cannot be a Python keyword like
if,for,class,True,None. Tryprint(False)and Python is happy. TryFalse = 0and you getSyntaxError. - ✗ No spaces or hyphens.
user-namelooks like subtraction;user namelooks like two separate things.
Style: snake_case
The Python community has a strong convention: variable names are lowercase with underscores between words. This is called snake_case.
Following the convention makes your code feel native to other Python programmers. Mixing styles makes it look amateur.
Names should describe meaning
A variable named n is fine for a tiny loop counter. A variable named n for the user's bank balance is a future bug. Give names that describe what the value MEANS, not just what shape it has.
Common mistakes
- Using
=to compare:if age = 18:is a syntax error. Comparison uses==. - Using a variable before assigning it:
print(age)beforeage = 25raisesNameError. - Assuming the type from the value's appearance:
"42"(a string) and42(an int) look similar but behave very differently."42" + 1is an error;42 + 1is43.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…