Thursday, May 14, 2026
Cohort 3 | Project CloudIgnite Topics: Python Basics Review, Exceptions, Control Flow, Loops, Lists, Dictionaries, CSV File Reading Duration: ~3 hours
⚠️ AWS CLF-C02 Relevance
This session is primarily a Python programming fundamentals lecture. The content does not directly map to AWS Certified Cloud Practitioner (CLF-C02) exam objectives. The CLF-C02 is a conceptual/business-level cloud exam — it does not require coding knowledge. However, the bash script and CSV file handling touched on briefly are general cloud practitioner skills useful for working in AWS environments (e.g., scripting for automation, reading config/data files). See the end of this document for a brief note on indirect relevance.
Key Takeaways
- Exceptions: runtime errors (IndexError, ZeroDivisionError, TypeError) — not syntax errors
- if/elif/else: colon syntax, indentation-based blocks,
.lower()for case-insensitive comparison - While loop: runs while condition is true;
breakexits loop,continueskips iteration - For loop:
range(start, stop, step)— upper bound always exclusive - String formatting:
.format(), f-strings,.join()method - CSV handling (Lab 113):
import csv,csv.reader(),with open()for safe file handling =is assignment,==is comparison — consistent across all languages
1. Python Basics Review (Quick Recap)
Topics considered already covered — no deep re-explanation needed:
- Basic math in Python (arithmetic operators)
- Variables – declaring, assigning, printing
- String concatenation – using the
+operator - Variable naming rules:
- Cannot start with a digit
- Cannot contain special characters (e.g.,
$,@) - Cannot use reserved keywords (e.g.,
def,int,float,for,while)
- Data types: use
floatfor decimal values (e.g.,1.7),intfor whole numbers +=operator – shortcut for incrementing:x += 1is the same asx = x + 1
2. Exceptions
What is an Exception?
An exception is an unexpected or abnormal event that occurs at runtime — not during syntax checking.
| Error Type | When detected | Example |
|---|---|---|
| Syntax error | At parse/compile time | Missing colon, invalid keyword |
| Runtime error (exception) | During execution | Index out of bounds, division by zero |
IDEs like VS Code will underline syntax errors in red. They cannot detect runtime exceptions before you run the code.
Common Exception Types
- IndexError – accessing a list index that doesn't exist
lst = [1, 2, 3] for i in range(4): # index 3 doesn't exist print(lst[i]) - ZeroDivisionError – dividing by zero
def div(a, b): return a / b div(10, 0) # raises ZeroDivisionError - TypeError – mixing incompatible types (e.g., concatenating a string with a number)
message = "Hello" print(message + 12) # TypeError # Fix: print(message + str(12)) - RecursionError / Stack Overflow – infinite recursion exceeds the call stack limit
def repeat(): repeat() repeat() # RecursionError: maximum recursion depth exceeded
Why Handle Exceptions?
- Unhandled exceptions cause the application to crash
- Crashes damage user experience and lower app store rankings
- Exception handling keeps applications stable and reliable
ℹ️ Python lets you set the recursion limit:
sys.setrecursionlimit(5000)— but increasing it is risky.
3. Control Flow – Conditional Statements
Syntax: if / elif / else
age = 18
if age > 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Key points:
- No brackets/parentheses required around the condition (unlike Java/C++)
- Each condition block ends with a colon
: - Indentation defines the code block — Python uses indentation, not
{} elifis Python's shorthand for "else if"- Once a condition is satisfied, all remaining conditions are skipped (even if they would also be true)
elseis optional
Real-world examples from lecture:
- Store open/closed based on time
- Low fuel warning if gas is below a threshold
- Building access based on employee badge
- Age classification (adult / teenager / child)
Demo: Banana Counter
banana = int(input("Enter banana count: "))
if banana >= 5:
print("I have a bunch of bananas")
elif banana >= 1 and banana <= 4:
print("I have a small bunch of bananas")
else:
print("I have no bananas")
⚠️ Remember to wrap
input()withint()when expecting a number —input()always returns a string.
4. Loops
While Loop
Runs as long as the condition is true.
i = 0
while i < banana:
print("Banana {}".format(i))
i += 1 # IMPORTANT: must increment, or it loops forever
Common mistake – infinite loop:
i = 0
while i < 5:
print(i)
# forgot i += 1 — this runs forever!
break – exit the loop immediately:
while i < 5:
if i == 3:
break # stops at 3; prints 0, 1, 2
print(i)
i += 1
continue – skip the rest of the current iteration:
while i < 5:
i += 1
if i == 3:
continue # skips print for i=3; prints 0, 1, 2, 4
print(i)
While loops work with any condition — not just integers. Float counters are valid too.
For Loop + range()
The range() function is flexible:
range(10) # 0 to 9
range(1, 10) # 1 to 9 (upper bound is exclusive)
range(1, 10, 2) # 1, 3, 5, 7, 9 (step of 2)
range(10, 0, -1) # 10, 9, 8 ... 1 (counting down)
range(10, 0, -2) # 10, 8, 6, 4, 2
Upper bound is always exclusive —
range(1, 10)goes up to 9, not 10.
5. Lists
lst = [1, 2, 3, 4] # list with values
lst = [] # empty list
lst.append(5) # add an item
lst = [i for i in range(1, 10)] # list comprehension (shortcut)
Key points:
- Declared with square brackets
[] - Can hold mixed types (int, string, float, etc.)
- Accessed by index starting at
0 - Index is always an integer; keys (for dictionaries) can be anything
6. Dictionaries
Similar to JSON objects — stores key-value pairs.
student = {
"ID123": {
"name": "Ahmad",
"email": "ahmad@example.com"
}
}
print(student["ID123"]) # prints full nested dict
print(student["ID123"]["name"]) # prints "Ahmad"
Iterating key-value pairs:
for key, value in student.items():
print(f"{key}: {value}")
Key differences vs Lists:
| Feature | List | Dictionary |
|---|---|---|
| Access by | Index (integer, starts at 0) | Key (any type) |
| Declaration | [] | {} |
| Use case | Ordered sequence | Named/labelled data |
7. String Formatting
.format() method
"Banana {}".format(i) # replaces {} with value of i
"Hello {}, age {}".format(name, age) # multiple substitutions
f-string (shortcut)
f"{key}: {value}" # modern Python shortcut, same result
.join() method
Joins list items into a single string with a separator:
names = ["abc", "xyz", "k"]
print("-".join(names)) # abc-xyz-k
print(",".join(names)) # abc,xyz,k
8. Reading a CSV File (Lab 113 Overview)
import csv
inventory_list = []
with open("carfleet.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
line_count = 0
for line in csv_reader:
if line_count == 0:
print("Columns: " + ", ".join(line))
else:
vehicle = {}
# map column values to dict keys
inventory_list.append(vehicle)
line_count += 1
print(inventory_list)
Key concepts used:
import csv– importing Python's built-in CSV librarywith open(...)– opens a file safely (auto-closes after block)csv.reader(..., delimiter=",")– reads CSV with comma as separator- Line 0 = header row (column names), not data
\n– invisible newline character that separates rowsline_count += 1– must increment to avoid re-reading header as data
ℹ️ Instructor note: Deep copy / shallow copy content in Lab 113 was skipped intentionally — considered too advanced for this stage. Resume with Lab 114 (if/elif/else) next session.
9. VS Code Tips
| Action | Shortcut |
|---|---|
| Multi-cursor (match word) | Select word → Ctrl+D (repeats for each match) |
| Multi-cursor (click anywhere) | Hold Alt + click each location |
| Delete backward | Backspace |
| Run Python file in terminal | python lab113.py (Windows) / python3 lab113.py (Mac/Linux) |
| Change directory (Windows) | cd D:\path\to\folder or D: then Enter to switch drives |
10. Key Reminders
=is the assignment operator (stores a value)==is the equality operator (compares two values)- This distinction is consistent across almost all programming languages
===(triple equals) exists in JavaScript/PHP — checks same object reference, not just value; Python does not have===- Python index always starts at 0
- Indentation is mandatory in Python — misplaced spaces cause
SyntaxError
AWS CLF-C02 Relevance
As mentioned at the top, this session does not cover AWS CLF-C02 exam content. The CLF-C02 exam tests cloud concepts, not programming skills.
That said, here is what indirectly connects:
| Session Content | Indirect CLF-C02 Relevance |
|---|---|
| Python scripting basics | AWS CLI and automation scripts often use Python (boto3) — useful for cloud practitioners in practice, but not tested on CLF-C02 |
| CSV file handling | Understanding data formats is relevant to AWS services like S3, Glue, Athena — but again, not tested on CLF-C02 at code level |
| Bash script mention (uploading files to Cloud9) | Basic shell scripting is useful for EC2 and Cloud9 environments |
| Cloud9 IDE (mentioned in lab context) | Cloud9 is an AWS service — a browser-based IDE. Knowing it exists is relevant to CLF-C02's coverage of AWS developer tools |
Bottom line: Focus your CLF-C02 study on cloud concepts (compute, storage, networking, security, pricing, shared responsibility model). This Python content supports your general AWS re/Start skills but won't appear on the exam.
Notes compiled from lecture — May 14, 2026