Intro to Python: Variables, Loops and Functions
Short lessons with practice problems that teach variables, conditionals, loops and functions in Python, with explanations for each answer.
Quick Reference
| Concept | Syntax Pattern | What It Does |
|---|---|---|
| Variable | score = 42 | Binds a name to a value |
| Conditional | if score >= 70: | Runs a block when condition is True |
| For Loop | for n in range(5): | Repeats a block 0, 1, 2, 3, 4 |
| List | nums = [2, 4, 6] | Stores an ordered, mutable sequence |
| Function | def double(x): return x * 2 | Packages reusable logic with parameters |
Core Concepts
Indentation Defines Blocks
Python uses consistent 4-space indentation instead of curly braces to group statements.
Zero-Based Indexing
The first element of a list or string is at index 0; negative index -1 accesses the last element.
Return vs. Print
print() displays text to the screen, whereas return sends a value back to the caller for further use.
Off-by-One Checks
Remember that range(1, 5) produces 1, 2, 3, 4—the stop value is excluded.
Self-Check Practice
1. What does list(range(2, 10, 2)) evaluate to?
Show worked answer
[2, 4, 6, 8].
2. Trace: total = 0; for x in [3, 5, 2]: total += x. What is total?
Show worked answer
10.
3. Why does '5' + 3 raise a TypeError in Python?
Show worked answer
Python does not implicitly add a string and an integer; convert with int('5') + 3.
Study Notes
- Trace loops on paper with a small variable table when a program outputs an unexpected value.
- Test edge cases like empty lists [] and zero inputs on every function you write.