Weeks 4–6 — Conditionals · Loops · Lists & Tuples
Control program flow with if/elif/else blocks. Learn nested conditions, the ternary expression, and how to structure complex decision logic. Automate repetitive tasks with for and while loops. Master range(), break, continue, and the rarely-known loop else clause. Work with Python's most-used sequence types. Master list CRUD operations, slicing syntax, common list methods, and tuple unpacking.
What you'll learn
- 1Use if / elif / else to branch on conditions
- 2Write nested if statements
- 3Use the ternary (conditional) expression
- 4Combine multiple conditions with and/or
- 5Understand truthiness of non-boolean values
- 6Iterate over a range with for/range()
- 7Use while for condition-driven loops
- 8Control loop flow with break and continue
- 9Explain the loop else clause
- 10Nest loops to produce 2D output
- 11Create and modify lists
- 12Access elements by index and slice
- 13Use append, insert, remove, pop, sort, reverse
- 14Understand the difference between list and tuple
- 15Unpack sequences into variables
Week 4 — Conditionals
Control program flow with if/elif/else blocks. Learn nested conditions, the ternary expression, and how to structure complex decision logic.
1. if / elif / else
score = int(input("Score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}")Python uses indentation (4 spaces) to define blocks. Mixing tabs and spaces causes IndentationError.
2. Ternary Expression
A concise single-line conditional: value_if_true if condition else value_if_false.
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult3. Truthiness
In Python, many non-boolean values evaluate as True or False in a boolean context.
| Value | Truthiness |
|---|---|
| 0, 0.0 | False |
| "" (empty string) | False |
| [], {}, () | False |
| None | False |
| Any non-zero number | True |
| Any non-empty string/list | True |
4. Common Mistakes
- Using = instead of == in a condition — this is a SyntaxError in Python (unlike C).
- Forgetting the colon after if/elif/else — SyntaxError.
- Overlapping conditions — put the most specific (highest/lowest) check first.
Week 5 — Loops
Automate repetitive tasks with for and while loops. Master range(), break, continue, and the rarely-known loop else clause.
1. for Loop & range()
for i in range(5): # 0 1 2 3 4
print(i, end=' ')
for i in range(1, 6): # 1 2 3 4 5
print(i, end=' ')
for i in range(0, 10, 2): # 0 2 4 6 8
print(i, end=' ')range(stop), range(start, stop), range(start, stop, step). The stop value is exclusive.
2. while Loop
n = 1
while n <= 5:
print(n)
n += 1
# Infinite loop with break
while True:
cmd = input("Command (quit to exit): ")
if cmd == "quit":
break
print(f"You entered: {cmd}")3. break, continue, else
for i in range(1, 11):
if i == 5:
continue # skip 5
if i == 8:
break # stop at 8
print(i, end=' ') # 1 2 3 4 6 7
for i in range(2, 10):
for j in range(2, i):
if i % j == 0:
break
else: # only runs if no break
print(f"{i} is prime")4. Nested Loops
for row in range(1, 4):
for col in range(1, 4):
print(f"{row}×{col}={row*col}", end=' ')
print()Output: 1×1=1 1×2=2 1×3=3 / 2×1=2 2×2=4 2×3=6 / 3×1=3 3×2=6 3×3=9
5. Common Mistakes
- Forgetting to increment the counter in a while loop → infinite loop. Always update the condition variable.
- range(1, 10) ends at 9, not 10. Off-by-one errors are very common.
- Modifying a list while iterating over it — iterate over a copy instead: for x in lst[:].
Week 6 — Lists & Tuples
Work with Python's most-used sequence types. Master list CRUD operations, slicing syntax, common list methods, and tuple unpacking.
1. Lists
Lists are ordered, mutable sequences. They can hold values of any type.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
print(len(fruits)) # 42. Slicing
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3]
print(nums[:3]) # [0, 1, 2]
print(nums[3:]) # [3, 4, 5]
print(nums[::2]) # [0, 2, 4] every other
print(nums[::-1]) # [5, 4, 3, 2, 1, 0] reversed3. Common List Methods
| Method | Description | Example |
|---|---|---|
| append(x) | Add to end | lst.append(5) |
| insert(i, x) | Insert at index | lst.insert(0, 'a') |
| remove(x) | Remove first match | lst.remove('a') |
| pop(i) | Remove & return at i | lst.pop() |
| sort() | Sort in-place | lst.sort() |
| reverse() | Reverse in-place | lst.reverse() |
| index(x) | Find first index | lst.index(3) |
| count(x) | Count occurrences | lst.count(2) |
4. Tuples
Tuples are like lists but immutable (cannot be changed after creation). Use them for fixed data.
point = (3, 4)
x, y = point # unpacking
print(f"x={x}, y={y}")
rgb = (255, 128, 0)
r, g, b = rgb
# swap without temp variable
a, b = 10, 20
a, b = b, a
print(a, b) # 20 105. List vs Tuple — and the copy trap
Lists and tuples look similar, but picking the right one prevents whole classes of bugs — and understanding how Python copies them prevents the rest.
| Question | List | Tuple |
|---|---|---|
| Mutable? | Yes — add / remove / reassign | No — fixed after creation |
| Use it for | A growing collection of similar items | A fixed record (x, y) or multiple return values |
| Works as a dict key? | No (unhashable) | Yes (hashable) |
| Syntax | [1, 2, 3] | (1, 2, 3) — the comma is what counts |
The copy trap (aliasing)
Assignment never copies a list — it just makes a second name for the SAME list. Mutating through one name shows up in the other. Copy explicitly when you need independence.
a = [1, 2, 3]
b = a # NOT a copy — same list object
b.append(4)
print(a) # [1, 2, 3, 4] <- surprised?
c = a[:] # shallow copy (also list(a) or a.copy())
c.append(5)
print(a) # unchangedA one-element tuple needs the comma: (5,) is a tuple, but (5) is just the integer 5. This bites everyone exactly once.
Common Mistakes (FAQ)
Q. Why does sorted_lst = lst.sort() give me None?
list.sort() sorts in place and returns None. Call it for the side effect (lst.sort()), or use sorted(lst) when you want a brand-new sorted list back.
Q. list[10] on a 5-item list crashes — how do I guard it?
That's an IndexError. Check len(lst) first, use a slice (lst[10:11] returns [] safely), or wrap the access in try/except IndexError.
Q. I did new = old, but editing new changed old too.
new = old doesn't copy — both names point to the same list. Use new = old[:], list(old), or old.copy() for a shallow copy (and copy.deepcopy for nested lists).
Q. Why isn't (5) a tuple?
Parentheses alone don't make a tuple — the comma does. Write (5,) for a one-element tuple; for multiple items like (1, 2) the comma is already there.
Q. When should I pick a tuple over a list?
Use a tuple for a fixed, heterogeneous record (a coordinate, an RGB color, multiple return values) or when you need a hashable dict key. Use a list when the collection grows, shrinks, or gets reordered.
💻 Examples
Run these examples and check the output yourself.
score = int(input("Score (0-100): "))
if score >= 90:
print("A — Excellent")
elif score >= 80:
print("B — Good")
elif score >= 70:
print("C — Average")
elif score >= 60:
print("D — Below average")
else:
print("F — Fail")
month = int(input("Month (1-12): "))
if month in [3, 4, 5]:
season = "Spring"
elif month in [6, 7, 8]:
season = "Summer"
elif month in [9, 10, 11]:
season = "Autumn"
else:
season = "Winter"
print(f"Month {month} is {season}.")
USER, PASS = "admin", "1234"
username = input("Username: ")
password = input("Password: ")
if username == USER and password == PASS:
print("Login successful!")
else:
print("Invalid credentials.")
for i in range(1, 10):
for j in range(1, 10):
print(f"{i*j:3d}", end='')
print()
n = int(input("N: "))
# for version
total = sum(range(1, n+1))
print(f"for: {total}")
# while version
total, i = 0, 1
while i <= n:
total += i
i += 1
print(f"while: {total}")
N: 100
for: 5050
while: 5050import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess (1-100): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! It took {attempts} attempts.")
break
names = ["Alice", "Bob", "Charlie"]
names.append("Diana")
names.insert(1, "Eve")
names.remove("Bob")
names.sort()
for i, name in enumerate(names, 1):
print(f"{i}. {name}")
1. Alice
2. Charlie
3. Diana
4. Evedata = list(range(10)) # [0..9]
print("First 5: ", data[:5])
print("Last 5: ", data[5:])
print("Middle: ", data[3:7])
print("Reversed: ", data[::-1])
print("Every 3rd:", data[::3])
First 5: [0, 1, 2, 3, 4]
Last 5: [5, 6, 7, 8, 9]
Middle: [3, 4, 5, 6]
Reversed: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Every 3rd: [0, 3, 6, 9]# Coordinates
point = (10, 20)
x, y = point
print(f"Point: ({x}, {y})")
# Swap two variables
a, b = 100, 200
a, b = b, a
print(f"a={a}, b={b}")
# Return multiple values from function
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"min={lo}, max={hi}")
Point: (10, 20)
a=200, b=100
min=1, max=9📝 Exercises
Try them yourself first, then open the solution to compare.
Triangle Classifier
Goal: Read three side lengths and classify the triangle.
- Input three positive numbers
- Check if triangle is valid (sum of any two sides > third)
- Classify: equilateral / isosceles / scalene
a: 5
b: 5
c: 8
Isosceles triangle▶Toggle solution
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if a+b > c and b+c > a and a+c > b:
if a == b == c:
print("Equilateral triangle")
elif a == b or b == c or a == c:
print("Isosceles triangle")
else:
print("Scalene triangle")
else:
print("Not a valid triangle")
Rock-Paper-Scissors (1 round)
Goal: Play one round of rock-paper-scissors against a hard-coded computer choice.
- Input: rock / paper / scissors
- Computer choice is fixed (e.g., 'rock')
- Print: win / lose / draw
▶Toggle solution
computer = "rock"
user = input("rock / paper / scissors: ").lower()
if user == computer:
print("Draw!")
elif (user == "paper" and computer == "rock") or \
(user == "scissors" and computer == "paper") or \
(user == "rock" and computer == "scissors"):
print("You win!")
else:
print("You lose!")
FizzBuzz
Goal: Print 1 to 100, replacing multiples of 3 with Fizz, 5 with Buzz, 15 with FizzBuzz.
- Use a for loop with range(1, 101)
- Check divisibility with %
- Print FizzBuzz for multiples of 15 first
▶Toggle solution
for i in range(1, 101):
if i % 15 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Star Pyramid
Goal: Print a right-aligned pyramid of stars.
- Read height N from input
- Row k prints (N-k) spaces then k stars
- Use nested loops
N: 5
*
**
***
****
*****▶Toggle solution
n = int(input('N: '))
for i in range(1, n+1):
print(' ' * (n-i) + '*' * i)
Grade Statistics
Goal: Read 5 scores, then print the sum, average, max, and min.
- Read 5 integers into a list
- Use sum(), max(), min(), len()
- Print all four statistics
Enter 5 scores:
85 90 78 92 88
Sum: 433 Avg: 86.6 Max: 92 Min: 78▶Toggle solution
scores = [int(input(f'Score {i+1}: ')) for i in range(5)]
print(f'Sum: {sum(scores)} Avg: {sum(scores)/len(scores):.1f} Max: {max(scores)} Min: {min(scores)}')
List Rotation
Goal: Rotate a list k positions to the right without using deque.
- Read a list and k from input
- Implement rotation using slicing
- Print the rotated list
List: 1 2 3 4 5
k: 2
[4, 5, 1, 2, 3]▶Toggle solution
lst = list(map(int, input('List: ').split()))
k = int(input('k: ')) % len(lst)
print(lst[-k:] + lst[:-k])
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗Comments 0
No comments yet. Be the first.
Only members can comment.
Comments with ads, abuse, personal information or illegal content are hidden or removed. Comments are shown with your nickname. Privacy Policy