0% Complete
Part 3
Module 7 of 17

Loops β€” For & While

Automate repetition. Loops are the backbone of efficient programming β€” they let you execute code multiple times without writing it repeatedly.

Why Loops Matter

Imagine printing numbers 1 to 100. Without loops, you'd write 100 print statements. With a loop: just 2 lines. Loops are essential for processing lists, reading files, and building algorithms.

The for Loop

A for loop iterates over a sequence (like a range, list, or string). It executes the code block once for each item in the sequence.

for_loop.py
# Basic for loop with range() for i in range(5): print("Iteration:", i) print("---") # range(start, stop, step) for i in range(2, 10, 3): print(i) # 2, 5, 8 print("---") # Looping through a string for char in "Python": print(char, "-", ord(char))
Output
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
---
2
5
8
---
P - 80
y - 121
t - 116
h - 104
o - 111
n - 110
range() Explained: range(5) gives 0,1,2,3,4. range(2,10,3) starts at 2, stops before 10, steps by 3 β€” giving 2,5,8. The stop value is exclusive.

The while Loop

A while loop runs as long as its condition is True. Use it when you don't know in advance how many iterations you need.

while_loop.py
# While loop β€” runs until condition is False count = 0 while count < 5: print("Count:", count) count += 1 # Must update! Otherwise infinite loop print("---") # break β€” exits the loop immediately for i in range(10): if i == 5: break print(i) # Prints 0,1,2,3,4 only print("---") # continue β€” skips to next iteration for i in range(5): if i == 2: continue print(i) # Prints 0,1,3,4 (skips 2)
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
---
0
1
2
3
4
---
0
1
3
4
Infinite Loop Danger: If you forget to update the condition variable in a while loop, it runs forever. Always ensure your loop has an exit path. Use break as a safety net.

Knowledge Check β€” Module 7

Q1: What does range(3, 8, 2) produce?

Module 8 of 17

Lists & Dictionaries

Two of Python's most powerful data structures for storing collections of data.

Lists β€” Ordered, Mutable Collections

Lists store multiple items in a single variable. They are ordered (items have a position), mutable (can be changed), and allow duplicates.

OperationCodeResult
Createfruits = ["apple", "banana"]List with 2 items
Accessfruits[0]"apple"
Addfruits.append("mango")Adds to end
Removefruits.remove("banana")Removes by value
Lengthlen(fruits)Number of items
lists.py
fruits = ["apple", "banana", "mango"] print(fruits[0]) # apple print(fruits[-1]) # mango (last item) print(len(fruits)) # 3 fruits.append("orange") print(fruits) # ['apple','banana','mango','orange'] # List slicing works like strings print(fruits[1:3]) # ['banana', 'mango'] # Nested lists matrix = [[1,2], [3,4], [5,6]] print(matrix[1][0]) # 3
Output
apple
mango
3
['apple', 'banana', 'mango', 'orange']
['banana', 'mango']
3

Dictionaries β€” Key-Value Pairs

Dictionaries store data as key: value pairs. They are unordered (Python 3.7+ maintains insertion order), mutable, and keys must be unique. Think of them like a real dictionary β€” you look up a word (key) to find its meaning (value).

dictionaries.py
student = { "name": "Alice", "age": 21, "grades": [85, 92, 78], "is_active": True } print(student["name"]) # Alice print(student["grades"][1]) # 92 # Add new key-value pair student["major"] = "CS" print(student.keys()) # dict_keys(['name','age',...]) print(student.values()) # dict_values(['Alice',21,...]) # Safe access with .get() print(student.get("phone", "N/A")) # N/A (no error!)
Output
Alice
92
dict_keys(['name', 'age', 'grades', 'is_active', 'major'])
dict_values(['Alice', 21, [85, 92, 78], True, 'CS'])
N/A
Lists vs Dictionaries: Use lists when order matters (queue, sequence). Use dictionaries when you need to look up values by a name/key (user profiles, settings, JSON data).

Knowledge Check β€” Module 8

How do you safely access a dictionary key that might not exist?

Module 9 of 17

Functions

Reusable blocks of code. Functions are the building blocks of clean, maintainable programs.

Why Functions?

Functions let you write code once and reuse it无数欑. They make code readable, testable, and modular. Instead of copying-pasting the same logic, you call a function.

functions.py
# Basic function def greet(): print("Hello from KODO!") greet() # Call the function # Function with parameters def add(a, b): return a + b result = add(5, 3) print("5 + 3 =", result) # Default parameters def welcome(name, greeting="Hello"): print(f"{greeting}, {name}!") welcome("Alice") # Hello, Alice! welcome("Bob", "Hi") # Hi, Bob! # Multiple return values def min_max(numbers): return min(numbers), max(numbers) low, high = min_max([3, 7, 2, 9]) print(f"Low: {low}, High: {high}")
Output
Hello from KODO!
5 + 3 = 8
Hello, Alice!
Hi, Bob!
Low: 2, High: 9
Return vs Print: return sends a value back to the caller. print() just displays it. A function without return returns None. Use return when you need the result for further computation.
Module 10 of 17

Practice Exercises

Apply everything from Modules 1-9 with hands-on problems.

10 Practice Problems

  1. Write a function that returns the factorial of a number.
  2. Create a program that counts vowels in a string.
  3. Build a simple calculator using functions.
  4. Find the largest number in a list without using max().
  5. Write a function that checks if a string is a palindrome.
  6. Create a dictionary from two lists (keys and values).
  7. Build a number guessing game using while loop.
  8. Write a function that returns Fibonacci sequence up to n.
  9. Create a program that removes duplicates from a list.
  10. Build a simple to-do list manager.
Module 11 of 17

File I/O β€” Reading & Writing Files

Persist data beyond program execution. Read from and write to files on your system.

File Modes

ModeDescription
'r'Read (default)
'w'Write (overwrites)
'a'Append (adds to end)
'r+'Read + Write
file_io.py
# Writing to a file with open("data.txt", "w") as f: f.write("Hello, KODO!\n") f.write("Python is amazing.") # Reading from a file with open("data.txt", "r") as f: content = f.read() print(content)
Output
Hello, KODO!
Python is amazing.
Always use with: The with statement automatically closes the file, even if an error occurs. No need to call f.close() manually.
Module 12 of 17

Exception Handling

Gracefully handle errors so your program doesn't crash unexpectedly.

exceptions.py
try: num = int(input("Enter a number: ")) result = 100 / num print("Result:", result) except ValueError: print("That's not a valid number!") except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Execution complete.")
Output (if user enters "0")
Cannot divide by zero!
Execution complete.