What is a Variable?¶
Try This First: Before reading, open Python and type
x = 5thenprint(x). Now typex = "hello"thenprint(x). Notice howxchanged? That is what a variable does.
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
A variable is a name that holds a value. You create it by writing a name, then =, then the value.
Embedding variables in strings (f-strings)¶
You can put variables directly inside a string by placing an f before the opening quote, then wrapping any variable name in curly braces {} where you want its value to appear. This is the most common and readable way to format strings in modern Python.
name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # Output: Hello, Alice! You are 30 years old.
The f tells Python: "treat anything in curly braces as a variable, not plain text." Without the f, {name} is just printed as the literal characters {name}.
print(f"Hello, {name}") # Output: Hello, Alice ✅
print("Hello, {name}") # Output: Hello, {name} ❌ (missing f)
Visualize It¶
See how Python stores variables in memory step by step: Open in Python Tutor
Think of it like a labeled jar. The label is the name. The contents are the value. You can:
- Look at the contents: print(name) shows Alice
- Replace the contents: name = "Alice" — now it holds "Alice"
- Use the contents in calculations: next_year = age + 1
Rules for naming variables¶
- Must start with a letter or underscore (not a number)
- Can contain letters, numbers, and underscores
- Case-sensitive:
Nameandnameare different variables - Convention: use
lowercase_with_underscores(called "snake_case")
Good names vs bad names¶
# Good — describes what the value represents
student_count = 42
max_temperature = 98.6
is_active = True
# Bad — vague or misleading
x = 42
temp = 98.6 # temp... temperature? temporary?
flag = True # flag for what?
Common mistakes¶
Using = instead of ==:
Forgetting quotes for text:
name = Alice # Error! Python thinks Alice is a variable name
name = "Alice" # Correct — quotes make it text (a string)
Using a variable before creating it:
print(score) # Error! score does not exist yet
score = 100 # This line creates it
print(score) # Now it works
Practice¶
- Level 00 / 04 Variables
- Level 00 / 05 Numbers and Math
- Level 00 / 06 Strings and Text
- Level 0 / 02 Calculator Basics
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|---|---|