← Back to Python series
🌱
Basic
if · elif · else · nested · ternary · for · while · range · break · continue · else · Indexing · Slicing · Methods · Unpacking

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.

ifelifelseconditionsternaryforwhilerangebreakcontinueloopslisttupleslicingmethodsunpacking
Duration
⏱ 2.5 hours + 2.5 hours + 2.5 hours
Level
📊 Beginner
Prerequisite
🎯 Week 3
OUTCOME
Write a grade classifier and a simple text-based menu / Build a multiplication table generator and a number guessing game / Build a contacts list that supports add, remove, search, and sort

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

python
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.

python
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

3. Truthiness

In Python, many non-boolean values evaluate as True or False in a boolean context.

ValueTruthiness
0, 0.0False
"" (empty string)False
[], {}, ()False
NoneFalse
Any non-zero numberTrue
Any non-empty string/listTrue

4. Common Mistakes

  1. Using = instead of == in a condition — this is a SyntaxError in Python (unlike C).
  2. Forgetting the colon after if/elif/else — SyntaxError.
  3. 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()

python
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

python
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

python
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

python
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

  1. Forgetting to increment the counter in a while loop → infinite loop. Always update the condition variable.
  2. range(1, 10) ends at 9, not 10. Off-by-one errors are very common.
  3. 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.

python
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))  # 4

2. Slicing

python
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]  reversed

3. Common List Methods

MethodDescriptionExample
append(x)Add to endlst.append(5)
insert(i, x)Insert at indexlst.insert(0, 'a')
remove(x)Remove first matchlst.remove('a')
pop(i)Remove & return at ilst.pop()
sort()Sort in-placelst.sort()
reverse()Reverse in-placelst.reverse()
index(x)Find first indexlst.index(3)
count(x)Count occurrenceslst.count(2)

4. Tuples

Tuples are like lists but immutable (cannot be changed after creation). Use them for fixed data.

python
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 10

5. 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.

QuestionListTuple
Mutable?Yes — add / remove / reassignNo — fixed after creation
Use it forA growing collection of similar itemsA 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.

python
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)         # unchanged
⚠️

A 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.

01_grade.py— Grade classifier with elif chain
CODE
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")
02_season.py— Season lookup from month number
CODE
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}.")
03_login.py— Simple username/password check
CODE
USER, PASS = "admin", "1234"
username = input("Username: ")
password = input("Password: ")
if username == USER and password == PASS:
    print("Login successful!")
else:
    print("Invalid credentials.")
01_times_table.py— Multiplication table 1–9
CODE
for i in range(1, 10):
    for j in range(1, 10):
        print(f"{i*j:3d}", end='')
    print()
02_sum_1_to_n.py— Sum 1 to N using for and while
CODE
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}")
▶ Output
N: 100
for: 5050
while: 5050
03_guess_number.py— Number guessing game with limited attempts
CODE
import 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
01_list_basics.py— CRUD operations on a list
CODE
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}")
▶ Output
1. Alice
2. Charlie
3. Diana
4. Eve
02_slicing.py— Slice operations
CODE
data = 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])
▶ Output
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]
03_tuple_unpack.py— Tuple creation and unpacking
CODE
# 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}")
▶ Output
Point: (10, 20)
a=200, b=100
min=1, max=9

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Triangle Classifier

Goal: Read three side lengths and classify the triangle.

Requirements
  • Input three positive numbers
  • Check if triangle is valid (sum of any two sides > third)
  • Classify: equilateral / isosceles / scalene
Sample I/O
a: 5
b: 5
c: 8
Isosceles triangle
▶Toggle solution
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")
Exercise 2

Rock-Paper-Scissors (1 round)

Goal: Play one round of rock-paper-scissors against a hard-coded computer choice.

Requirements
  • Input: rock / paper / scissors
  • Computer choice is fixed (e.g., 'rock')
  • Print: win / lose / draw
▶Toggle solution
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!")
Exercise 3

FizzBuzz

Goal: Print 1 to 100, replacing multiples of 3 with Fizz, 5 with Buzz, 15 with FizzBuzz.

Requirements
  • Use a for loop with range(1, 101)
  • Check divisibility with %
  • Print FizzBuzz for multiples of 15 first
▶Toggle solution
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)
Exercise 4

Star Pyramid

Goal: Print a right-aligned pyramid of stars.

Requirements
  • Read height N from input
  • Row k prints (N-k) spaces then k stars
  • Use nested loops
Sample I/O
N: 5
    *
   **
  ***
 **** 
*****
▶Toggle solution
SOLUTION
n = int(input('N: '))
for i in range(1, n+1):
    print(' ' * (n-i) + '*' * i)
Exercise 5

Grade Statistics

Goal: Read 5 scores, then print the sum, average, max, and min.

Requirements
  • Read 5 integers into a list
  • Use sum(), max(), min(), len()
  • Print all four statistics
Sample I/O
Enter 5 scores:
85 90 78 92 88
Sum: 433  Avg: 86.6  Max: 92  Min: 78
▶Toggle solution
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)}')
Exercise 6

List Rotation

Goal: Rotate a list k positions to the right without using deque.

Requirements
  • Read a list and k from input
  • Implement rotation using slicing
  • Print the rotated list
Sample I/O
List: 1 2 3 4 5
k: 2
[4, 5, 1, 2, 3]
▶Toggle solution
SOLUTION
lst = list(map(int, input('List: ').split()))
k = int(input('k: ')) % len(lst)
print(lst[-k:] + lst[:-k])
Example code / lecture materials

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