Python Programming Basics β IGCSE Level
Nine lessons that teach you Python from zero, plus 100 practice exercises β one a day β that build the programming skills for IGCSE Computer Science Paper 2 (0478 and 4CP0). Section 1 and Day 1 are free β sign in with Google to unlock the rest.
Course map: Lessons 1β9 (Python Basics) Β· Practice Modules 1β9 (Days 1β100 + 5 Bonus) Β· 105 programs in total Β· Exam target: May/June 2027
Python Programming Basics Β· Notes by Tr. Wai Lin Htet
Try it now β say hello
Type your name and press Run. This is Day 1’s program, running right here.
first_name = input("Enter your first name: ")
print("Hello", first_name)
Output: Hello Alice
Try it before you sign in
No sign-in needed for these β two video lessons and a sample from a lesson and a practice day, so you can see how the course teaches before you join.
Pseudocode Revision Part 2
Lesson sample β Variables
name = "Alice"
age = 20
print("Name:", name)
print("Age:", age)
Day 1 sample β Hello [First Name]
first_name = input("Enter your first name: ")
print("Hello", first_name)
Course list
Nine lessons and nine practice modules, in one combined page. Section 1 and Day 1 are free β sign in with Google to unlock Sections 2β9 and Days 2β100.
Lessons Β· Python Basics
Practice Β· 100 Days of Python
How to get access
1) Sign in with Google on the login page. 2) Your teacher approves your account. 3) Your courses appear on your dashboard β open this page from there.
Lessons Β· Python Basics
Nine lessons, from your first program to dictionaries. Each lesson ends with a “Try it” task and two check-yourself questions. Section 1 is free β the rest unlock after sign-in + teacher approval.
Section 1 β Python Basics
What Python is, and your first program.
1.1What is Python?
Python is a high-level programming language. It is easy to learn, readable and widely used. We can write and run programs using Python.
- High-level language
- Python reads almost like English, so you can focus on solving the problem instead of fighting the language.
- Easy to learn
- Python has a small set of rules. Most students write their first working program in the first lesson.
- Readable code
- Python code looks like the idea it describes β which is why examiners and teachers can read it quickly.
- Many uses
- Artificial intelligence (AI), web development, data analysis, games, automation β the same language is used for all of them.
1.2Your first program
print() shows text on the screen. The text goes inside the brackets, in quotes.
print("Hello, World!")
Output:
Hello, World!
Try it
Change the message inside print() to your own name, then run the program.
print("Hello, Alice!")1.3Check yourself
- What does “high-level language” mean? [2]
- Name two things Python is used for. [2]
- A high-level language is close to human language, so it is easy to read and write β Python handles the low-level details (like memory) for you.
- Any two from: artificial intelligence (AI), web development, data analysis, games, automation.
Practise next: Module 1 β Days 1β11 (input, output and arithmetic).
Section 2 β Variables
Storing values under a name.
Section 2 β Variables
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
2.1What is a variable?
A variable stores a value (e.g., text, number, etc.). We can give a name to a variable. The value can be changed during the program.
name = "Alice"
age = 20
print("Name:", name)
print("Age:", age)
Output:
Name: Alice Age: 20
The = sign assigns a value to a variable β it does not mean “equals”. Read name = "Alice" as “name gets the value Alice”.
2.2Rules for variable names
- Letters, numbers, underscore
- Use letters, numbers and underscore (_). No other symbols.
- Start with a letter or underscore
- A name must start with a letter or underscore β never a number.
- No spaces
my ageis not allowed. Usemy_ageinstead.- Meaningful names
- Use meaningful names (e.g., name, age, total) so anyone reading your code knows what the variable holds.
- Using a space in a name:
first name = "Alice"is a syntax error. - Starting a name with a number:
1st_nameis not allowed. - Using a meaningless name like
xwhenagewould be clear.
Try it
Create a variable called city and set it to your town. Print it. Then change it to another town and print it again.
city = "Yangon" print(city) city = "Mandalay" print(city)
2.3Check yourself
- What is wrong with this variable name:
my age = 20? [1] - What does
name = "Alice"do? [2]
- It contains a space β variable names cannot contain spaces. Write
my_ageinstead. - It creates a variable called
nameand stores the text"Alice"in it.
Practise next: Module 1 β Days 1β11.
Section 3 β Data Types
int, float, str and bool.
Section 3 β Data Types
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
3.1What is a data type?
A data type tells Python what kind of data a variable stores. Python works out the type from the value β you do not declare it.
| Data type | Description | Example |
|---|---|---|
| int | Whole number (integer) | count = 10 |
| float | Decimal number (floating-point) | height = 5.5 |
| str | Text (string) | name = "Bob" |
| bool | Logical value (True or False) | is_student = True |
count = 10 height = 5.5 name = "Bob" is_student = True print(count) print(height) print(name) print(is_student)
Output:
10 5.5 Bob True
10 + 5 is 15 (numbers add), but "10" + "5" is "105" (text joins). When a value comes from input() it is always a string β cast it with int() or float() before doing arithmetic.Try it
Create a variable score = 95 and a variable passed = True. Print both.
score = 95 passed = True print(score) print(passed)
3.2Check yourself
- What data type is 5.5? [1]
- What data type is True? [1]
- float β a decimal number.
- bool β a logical value (True or False).
Practise next: Module 1 β Days 1β11.
Section 4 β Basic Operations
Arithmetic operators: +, -, *, /, //, %, **.
Section 4 β Basic Operations
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
4.1Operators
Python can perform calculations using operators. Common operators: addition, subtraction, multiplication, division, etc.
| Operator | Meaning | Example |
|---|---|---|
| + | Add | 10 + 3 = 13 |
| - | Subtract | 10 - 3 = 7 |
| * | Multiply | 10 * 3 = 30 |
| / | Divide | 10 / 3 = 3.33 |
| // | Floor division | 10 // 3 = 3 |
| % | Modulus (remainder) | 10 % 3 = 1 |
| ** | Power (exponent) | 10 ** 3 = 1000 |
print(10 + 3) # 13 print(10 - 3) # 7 print(10 * 3) # 30 print(10 / 3) # 3.33 (rounded β Python prints 3.3333333333333335) print(10 // 3) # 3 print(10 % 3) # 1 print(10 ** 3) # 1000
// gives the whole-number part of a division and % gives the remainder. Together they split a division: 10 Γ· 3 is 3 remainder 1. You will use this pair in Day 11 and Day 33.4.2Order of operations
Python follows BODMAS: brackets first, then powers, then multiplication and division, then addition and subtraction. When in doubt, use brackets β they make the order clear.
print(2 + 3 * 4) # 14 β multiplication first print((2 + 3) * 4) # 20 β brackets first
Try it
Work out 25 // 4 and 25 % 4. What do they tell you about 25 Γ· 4?
print(25 // 4) # 6 print(25 % 4) # 1 # 25 Γ· 4 is 6 remainder 1
4.3Check yourself
- What is 10 % 3? [1]
- What is 2 ** 4? [1]
- 1 β the remainder when 10 is divided by 3.
- 16 β 2 to the power of 4 (2 Γ 2 Γ 2 Γ 2).
Practise next: Module 1 β Days 1β11 and Module 4 β Days 27β34.
Section 5 β Conditionals
if, elif and else.
Section 5 β Conditionals
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
5.1Making decisions
Conditionals are used to make decisions in a program. Python runs different code based on a condition (True or False).
age = 18
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Output:
You are an adult.
- if
- Use if to check a condition.
- elif
- Use elif for another condition.
- else
- Use else for the default case.
- Comparison operators
- Conditions often use comparison operators (e.g., >=, <=, ==, !=).
Indentation matters. The lines inside an if, elif or else must be indented by the same amount (4 spaces). Python checks the branches in order and runs the first one whose condition is True β then it skips the rest.
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
- Writing
=(assign) instead of==(compare) inside a condition. - Forgetting the colon
:at the end of theifline. - Forgetting to indent the lines inside the branch.
Try it
Change age to 15 and work out what the program prints. Then change it to 8.
age = 15
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
# Output: You are a teenager.5.2Check yourself
- What does
if age >= 18:check? [1] - When does the
elseblock run? [2]
- Whether age is 18 or more.
- When none of the if or elif conditions is True.
Practise next: Module 2 β Days 12β19.
Section 6 β Loops
for and while loops.
Section 6 β Loops
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
6.1Repeating code
A loop repeats a block of code multiple times. Python has two main types of loops:
- for loop
- Repeat for a set of items.
- while loop
- Repeat while a condition is True.
6.2for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple banana cherry
The loop variable fruit takes each item from the list in turn. range(5) gives the numbers 0 to 4 β useful when you want to repeat a fixed number of times.
6.3while loop
count = 1
while count <= 5:
print("Count:", count)
count = count + 1
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
- Forgetting to change the condition inside a while loop β it runs forever (an infinite loop).
- Using a while loop when a for loop is clearer (when you know how many times to repeat).
Try it
Use a for loop to print the numbers 1 to 5. Then do the same with a while loop.
for i in range(1, 6):
print(i)
count = 1
while count <= 5:
print(count)
count = count + 16.4Check yourself
- When should you use a for loop instead of a while loop? [2]
- What happens if a while loop's condition never becomes False? [1]
- When you know how many times to repeat β a fixed number of times, or once per item in a list.
- It runs forever β an infinite loop.
Practise next: Module 5 β Days 35β44 and Module 6 β Days 45β51.
Section 7 β Functions
def, return and parameters.
Section 7 β Functions
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
7.1What is a function?
A function is a reusable block of code. It helps to organise code, avoid repetition and make programs easier to read.
def greet(name):
return f"Hello, {name}!"
message = greet("Python")
print(message)
Output:
Hello, Python!
- def
- Use def to define a function.
- return
- Use return to send a value back.
- Parameters
- A function can take parameters (e.g., name).
A function does nothing until you call it. greet("Python") calls the function with the argument "Python", and return sends the result back to the caller. The value that comes back can be stored in a variable, like message above.
Try it
Write a function double(number) that returns number * 2. Call it with 7 and print the result.
def double(number):
return number * 2
print(double(7)) # 147.2Check yourself
- What does return do? [2]
- What is the difference between a parameter and an argument? [2]
- It sends a value back to the place that called the function.
- A parameter is the name in the function definition (e.g., name); an argument is the value passed when calling it (e.g., “Python”).
Practise next: Module 9 β Days 86β100 and the Bonus questions (Days 101β105).
Section 8 β Lists
Ordered collections and list methods.
Section 8 β Lists
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
8.1What is a list?
A list is an ordered collection of items. It can store different types of data (e.g., numbers, text, etc.).
numbers = [1, 2, 3, 4, 5] numbers.append(6) numbers.insert(0, 0) numbers.remove(3) numbers.pop() print(numbers)
Output:
[0, 1, 2, 4, 5]
Follow the steps: append(6) adds 6 at the end β [1, 2, 3, 4, 5, 6]; insert(0, 0) puts 0 at index 0 β [0, 1, 2, 3, 4, 5, 6]; remove(3) takes out the 3 β [0, 1, 2, 4, 5, 6]; pop() removes the last item (6) β [0, 1, 2, 4, 5].
| Method | What it does |
|---|---|
| append(x) | Add an item at the end |
| insert(i, x) | Insert an item at index i |
| remove(x) | Remove the first occurrence of x |
| pop() | Remove and return the last item |
| clear() | Remove all items |
The first item is at index 0: numbers[0] is 1 in the original list. len(numbers) gives the number of items.
Try it
Make a list of your three favourite foods. Append one more, then print the list.
foods = ["Laphet", "Mohinga", "Pizza"]
foods.append("Shan Noodles")
print(foods)8.2Check yourself
- What is the index of the first item in a list? [1]
- What does numbers.pop() do? [1]
- 0.
- It removes and returns the last item in the list.
Practise next: Module 7 β Days 52β69.
Section 9 β Dictionaries
Key-value pairs.
Section 9 β Dictionaries
This section is for approved SrWL Learning students. Sign in with Google to unlock it β Section 1 is free to read now.
9.1What is a dictionary?
A dictionary stores data as key-value pairs (e.g., name and age). Each key must be unique and cannot be changed (immutable).
person = {"name": "Alice", "age": 20, "city": "New York"}
print(person["name"])
person["age"] = 21
person["email"] = "alice@example.com"
del person["city"]
print(person)
Output:
Alice
{'name': 'Alice', 'age': 21, 'email': 'alice@example.com'}
- Key-value pairs
- A dictionary uses key-value pairs.
- Unique keys
- Keys must be unique (e.g., “name”, “age”).
- Values can change
- The value can be changed (update).
- del
- Use del to remove a key-value pair.
person["name"]. If the key does not exist, Python raises a KeyError β check with in first (if "email" in person:) or use .get() (Day 60).Try it
Make a dictionary for a book with keys title, author and year. Add a new key pages, then print the dictionary.
book = {"title": "Python Basics", "author": "SrWL", "year": 2026}
book["pages"] = 120
print(book)9.2Check yourself
- How do you get the value for the key “name” from the dictionary person? [1]
- Can a dictionary have two keys with the same name? [1]
person["name"].- No β keys must be unique.
Practise next: Module 7 β Days 52β69 (Days 60β61 and 68 use dictionaries).
Practice Β· 100 Days of Python
One program a day for 100 days, in 9 modules β plus 5 bonus challenges. Try each exercise first, then press “Show solution” to check your code. Day 1 is free β the rest unlock after sign-in + teacher approval.
Module 1 β Basic Input, Output, and Arithmetic
Days 1β11 Β· Questions 001β011. Reading input, printing output, and doing arithmetic. Builds on Lessons 1β4.
Day 1 Hello [First Name] Q001
Write a program that asks for your first name, then prints: Hello [your name] Example: Enter your first name: Alice Hello Alice
first_name = input("Enter your first name: ")
print("Hello", first_name)
How it works: input() reads text into a variable, and print() with a comma adds a space automatically.
Day 2 β Hello [First Name] [Surname]
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 2 Hello [First Name] [Surname] Q002
Ask for a first name AND a surname, then print them together: Hello Alice Smith Hint: use + to join strings together.
first_name = input("Enter your first name: ")
surname = input("Enter your surname: ")
print("Hello " + first_name + " " + surname)
How it works: + joins strings together. You must add " " yourself β Python does not add spaces when you use +.
Day 3 β Single-line Joke Format
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 3 Single-line Joke Format Q003
Print this joke with ONE print() statement, on two lines: What do you call a bear with no teeth? A gummy bear! Hint: there is a special character that makes a new line.
print("What do you call a bear with no teeth?\nA gummy bear!")
How it works: \n is the newline escape sequence β it moves the rest of the text to a new line inside one print().
Day 4 β Two Number Accumulation
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 4 Two Number Accumulation Q004
Ask for two numbers, add them, and print the total: Enter first number: 5 Enter second number: 7 The total is 12 Hint: input() gives you text β you must convert it to a number first.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print(f"The total is {total}")
How it works: int() converts the input text to a whole number, so + does real addition instead of joining text.
Day 5 β Three Number Mixed Arithmetic
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 5 Three Number Mixed Arithmetic Q005
Ask for three numbers. Add the first two, then multiply the result by the third number. Example: (4 + 6) * 3 = 30 Hint: brackets change the order of calculation.
n1 = int(input("Number 1: "))
n2 = int(input("Number 2: "))
n3 = int(input("Number 3: "))
answer = (n1 + n2) * n3
print("The answer is", answer)
How it works: brackets force the addition to happen before the multiplication (BODMAS rule).
Day 6 β Pizza Slice Deductor
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 6 Pizza Slice Deductor Q006
A pizza has some slices. You eat some. How many are left? Slices started with: 8 Slices eaten: 3 You have 5 slices left.
start = int(input("Slices started with: "))
eaten = int(input("Slices eaten: "))
left = start - eaten
print(f"You have {left} slices left.")
How it works: simple subtraction β store the result in a new variable and print it with an f-string.
Day 7 β Age Modifier Target
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 7 Age Modifier Target Q007
Ask for a name and an age, then print how old the person will be on their next birthday: Name: Alice Age: 20 Alice next birthday you will be 21
name = input("Name: ")
age = int(input("Age: "))
print(f"{name} next birthday you will be {age + 1}")
How it works: you can do arithmetic (age + 1) right inside an f-string.
Day 8 β Bill Splitter Interface
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 8 Bill Splitter Interface Q008
Split a restaurant bill equally between friends: Total price of bill: 50 Number of diners: 4 Each person must pay: $12.50 Hint: the answer must show exactly 2 decimal places.
bill = float(input("Total price of bill: "))
diners = int(input("Number of diners: "))
pay = bill / diners
print(f"Each person must pay: ${pay:.2f}")
How it works: float() allows decimal numbers, and :.2f formats the answer to exactly 2 decimal places.
Day 9 β Days to Time Metric Converter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 9 Days to Time Metric Converter Q009
Ask for a number of days, then convert it to hours, minutes and seconds: Enter number of days: 2 In 2 days there are 48 hours, 2880 minutes, and 172800 seconds.
days = int(input("Enter number of days: "))
hours = days * 24
minutes = hours * 60
seconds = minutes * 60
print(f"In {days} days there are {hours} hours, {minutes} minutes, and {seconds} seconds.")
How it works: each step reuses the previous answer β days to hours, hours to minutes, minutes to seconds.
Day 10 β Kilogram to Pound Scale Converter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 10 Kilogram to Pound Scale Converter Q010
Convert kilograms to pounds. 1 kg = 2.204 pounds. Weight in Kilograms: 70 That equates to 154.28 pounds. Hint: round the answer to 2 decimal places.
kg = float(input("Weight in Kilograms: "))
lbs = kg * 2.204
print(f"That equates to {round(lbs, 2)} pounds.")
How it works: multiply by 2.204, then round() keeps the answer to 2 decimal places.
Day 11 β Division Threshold Inspector
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 11 Division Threshold Inspector Q011
Ask for a number over 100 and a number under 10. How many whole times does the small number go into the big number? Enter a number over 100: 120 Enter a number under 10: 7 7 goes into 120 exactly 17 times. Hint: use the operator that drops the decimal part.
big = int(input("Enter a number over 100: "))
small = int(input("Enter a number under 10: "))
times = big // small
print(f"{small} goes into {big} exactly {times} times.")
How it works: // is floor division β it gives the whole number of times and drops the remainder.
Builds on Sections 1β4 β review the lesson if you get stuck.
Module 2 β Conditional Logic
Days 12β19 Β· Questions 012β019. Making decisions with if, elif and else. Builds on Lesson 5.
Day 12 β Structural Comparison Sorting
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 12 Structural Comparison Sorting Q012
Sort two numbers into ascending order! Write a program that asks for two numbers and prints them smallest first. Example: Num 1: 8 Num 2: 3 Output: 3 8
n1 = int(input("Num 1: "))
n2 = int(input("Num 2: "))
if n1 > n2:
print(n2, n1)
else:
print(n1, n2)
How it works: If the first number is bigger, print them swapped. Otherwise, print them as they are. Only two branches β if / else.
Day 13 β Boundary Gate Check
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 13 Boundary Gate Check Q013
Boundary Gate Check! Ask the user for a number under 20. If it is 20 or more, print "Too high". Otherwise, print "Thank you". Example: Enter a number under 20: 25 Output: Too high
num = int(input("Enter a number under 20: "))
if num >= 20:
print("Too high")
else:
print("Thank you")
How it works: >= means "greater than or equal to". 20 itself is "Too high" β the boundary is included. This is a validation check: it guards against bad input.
Day 14 β Range Inclusion Gate
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 14 Range Inclusion Gate Q014
Range Inclusion Gate! Ask for a value between 10 and 20. If it is inside the range, print "Thank you". Otherwise, print "Incorrect answer". Example: Enter a value between 10 and 20: 15 Output: Thank you
num = int(input("Enter a value between 10 and 20: "))
if num >= 10 and num <= 20:
print("Thank you")
else:
print("Incorrect answer")
How it works: and joins two conditions β BOTH must be True. num >= 10 checks the lower edge. num <= 20 checks the upper edge. 10 and 20 themselves are inside the range.
Day 15 β Case Tolerant Match System
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 15 Case Tolerant Match System Q015
Case Tolerant Match! Ask for a favourite colour. If it is red β in any capitalisation β print "I like red too". Otherwise, print "I don't like ___, I prefer red". Example: Enter favourite colour: RED Output: I like red too
colour = input("Enter favourite colour: ")
if colour == "red" or colour == "RED" or colour == "Red":
print("I like red too")
else:
print(f"I don't like {colour}, I prefer red")
How it works: or joins choices β ANY one being True is enough. "red", "RED" and "Red" are all accepted. The f-string puts the user's colour into the message.
Day 16 β Case Normalizer & Nested Blocks
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 16 Case Normalizer & Nested Blocks Q016
Nested If Blocks! Ask "Is it raining?" If yes, ask "Is it windy?" β’ Windy β "It is too windy for an umbrella" β’ Not windy β "Take an umbrella" If not raining β "Enjoy your day" Example: Is it raining? yes Is it windy? no Output: Take an umbrella
rain = input("Is it raining? ").lower()
if rain == "yes":
wind = input("Is it windy? ").lower()
if wind == "yes":
print("It is too windy for an umbrella")
else:
print("Take an umbrella")
else:
print("Enjoy your day")
How it works: .lower() converts the answer to lowercase β "YES", "Yes" and "yes" all become "yes". The second if is INSIDE the first β a nested if. The windy question is only asked when it is raining.
Day 17 β Cascade Multi-Branch Registry
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 17 Cascade Multi-Branch Registry Q017
Age Check β elif Cascade! Ask for an age and print: β’ 18 or older β "You can vote" β’ 17 β "You can learn to drive" β’ 16 β "You can buy a lottery ticket" β’ Anything else β "You can go Trick-or-Treating" Example: Age check: 17 Output: You can learn to drive
age = int(input("Age check: "))
if age >= 18:
print("You can vote")
elif age == 17:
print("You can learn to drive")
elif age == 16:
print("You can buy a lottery ticket")
else:
print("You can go Trick-or-Treating")
How it works: elif = "else if" β Python checks the branches in order. As soon as one branch matches, it stops. Order matters: >= 18 must come first, or 18 would never reach the vote branch. else catches everything that is left.
Day 18 β Range Status Evaluator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 18 Range Status Evaluator Q018
Range Status Evaluator! Ask for a value and print: β’ Less than 10 β "Too low" β’ 10 to 20 β "Correct" β’ More than 20 β "Too high" Example: Value: 25 Output: Too high
num = int(input("Value: "))
if num < 10:
print("Too low")
elif num >= 10 and num <= 20:
print("Correct")
else:
print("Too high")
How it works: Three bands: low, correct, high. The elif checks the middle band with and. else catches everything above 20 β no third condition needed. Compare with Day 14: same range, but now three outcomes instead of two.
Day 19 β Numeric Route Menu Switch
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 19 Numeric Route Menu Switch Q019
Menu Switch! Ask the user to enter 1, 2 or 3 and print: β’ 1 β "Thank you" β’ 2 β "Well done" β’ 3 β "Correct" β’ Anything else β "Error message" Example: Enter 1, 2 or 3: 2 Output: Well done
choice = input("Enter 1, 2 or 3: ")
if choice == "1":
print("Thank you")
elif choice == "2":
print("Well done")
elif choice == "3":
print("Correct")
else:
print("Error message")
How it works: choice stays a STRING β no int() here. "1" (text) is not the same as 1 (number). The else is the safety net: any unexpected input gets an error message instead of crashing. This is the menu pattern β used in real programs.
Builds on Section 5 β review the lesson if you get stuck.
Module 3 β String Manipulation
Days 20β26 Β· Questions 020β026. Working with text: length, joining, slicing, changing case.
Day 20 β String Character Counter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 20 String Character Counter Q020
Ask for a first name, then print how many characters it has. Example: Enter first name: Alice β 5
name = input("Enter first name: ")
print(len(name))
How it works: len() returns the number of characters in a string β spaces count too.
Day 21 β Integrated Name Array Analyst
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 21 Integrated Name Array Analyst Q021
Ask for a first name and a surname, join them with a space, then print the full name and its length. Example: First name: Alice, Surname: Smith β Alice Smith 11
first = input("First name: ")
sur = input("Surname: ")
full = first + " " + sur
print(full, len(full))
How it works: + joins strings together, and len() counts every character including the space between the names.
Day 22 β Title Casing Combiner
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 22 Title Casing Combiner Q022
Ask for a first name and a surname in lowercase, then print them properly capitalised. Example: alice smith β Alice Smith
first = input("First name lower: ")
sur = input("Surname lower: ")
full = (first + " " + sur).title()
print(full)
How it works: .title() capitalises the first letter of every word in a string.
Day 23 β Substring Index Slicer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 23 Substring Index Slicer Q023
Ask for a line of text, print its length, then ask for a start and an end index and print that slice. Example: rhyme "Humpty Dumpty", start 0, end 6 β Humpty
rhyme = input("Type a nursery rhyme line: ")
print("Length:", len(rhyme))
start = int(input("Start index: "))
end = int(input("End index: "))
print(rhyme[start:end])
How it works: Slicing uses [start:end] β the start index is included, the end index is not. Indexes start at 0.
Day 24 β Uppercase Converter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 24 Uppercase Converter Q024
Ask for any word and print it in UPPERCASE. Example: hello β HELLO
word = input("Type any word: ")
print(word.upper())
How it works: .upper() returns the string with every letter capitalised.
Day 25 β Conditional Name Formatter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 25 Conditional Name Formatter Q025
Ask for a first name. If it is shorter than 5 letters, ask for a surname and print the full name in UPPERCASE. Otherwise print the first name in lowercase. Example: Bob (surname Smith) β BOBSMITH; Alice β alice
first = input("Enter first name: ")
if len(first) < 5:
sur = input("Enter surname: ")
print((first + sur).upper())
else:
print(first.lower())
How it works: len() inside a condition lets the program choose a path based on the length of the text.
Day 26 β Pig Latin Linguistic Processor
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 26 Pig Latin Linguistic Processor Q026
Ask for a word and convert it to Pig Latin: if it starts with a vowel, add "way"; otherwise move the first letter to the end and add "ay". Example: apple β appleway; banana β ananabay
word = input("Enter a word: ").lower()
vowels = "aeiou"
if word[0] in vowels:
print(word + "way")
else:
print(word[1:] + word[0] + "ay")
How it works: word[0] is the first letter, word[1:] is everything after it, and "in" checks membership β "a" in "aeiou" is True.
Builds on Sections 3 and 9 β review the lesson if you get stuck.
Module 4 β Math Functions and Rounding
Days 27β34 Β· Questions 027β034. Decimal numbers, rounding, and the math module.
Day 27 β Float Scaler Processing
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 27 Float Scaler Processing Q027
Ask for a long decimal number and print double its value. Example: 3.14159 β 6.28318
num = float(input("Enter long decimal float: "))
print(num * 2)
How it works: float() converts the input text to a decimal number so you can do decimal arithmetic.
Day 28 β Two-Place Decimal Rounder
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 28 Two-Place Decimal Rounder Q028
Ask for a long decimal number, double it, and print the answer rounded to 2 decimal places. Example: 3.14159 β 6.28
num = float(input("Enter long decimal float: "))
print(round(num * 2, 2))
How it works: round(value, 2) rounds a number to 2 decimal places.
Day 29 β System Square Root Extractor
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 29 System Square Root Extractor Q029
Ask for a whole number over 500 and print its square root rounded to 2 decimal places. Example: 625 β 25.0
import math
num = int(input("Value over 500: "))
print(round(math.sqrt(num), 2))
How it works: import math gives you math.sqrt() for square roots β the math module must be imported before you use it.
Day 30 β Pi Constant Precision Printer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 30 Pi Constant Precision Printer Q030
Print the value of pi rounded to 5 decimal places. Example output: 3.14159
import math print(round(math.pi, 5))
How it works: math.pi is a constant built into the math module β more accurate than typing 3.14 yourself.
Day 31 β Circle Area Resolver
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 31 Circle Area Resolver Q031
Ask for the radius of a circle and print its area (pi Γ radius squared). Example: Radius: 5 β Area: about 78.54
import math
r = float(input("Radius: "))
area = math.pi * (r ** 2)
print("Area:", area)
How it works: ** is the power operator β r ** 2 means r squared.
Day 32 β Cylinder Volume Computer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 32 Cylinder Volume Computer Q032
Ask for the radius and depth of a cylinder and print its volume (pi Γ radius squared Γ depth), rounded to 3 decimal places. Example: Radius 3, Depth 5 β Volume: 141.372
import math
r = float(input("Radius: "))
depth = float(input("Depth: "))
vol = (math.pi * (r ** 2)) * depth
print("Volume:", round(vol, 3))
How it works: Build the volume in one expression, then round() the result when you print it.
Day 33 β Division Composition Inspector
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 33 Division Composition Inspector Q033
Ask for a numerator and a denominator, then print how many whole times the denominator goes into the numerator and what is left over. Example: 10 divided by 3 is 3 with 1 remaining
n1 = int(input("Numerator: "))
n2 = int(input("Denominator: "))
print(f"{n1} divided by {n2} is {n1 // n2} with {n1 % n2} remaining")
How it works: // is floor division (the whole part) and % is the remainder β together they describe any division.
Day 34 β Geometrical Interface Gateway
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 34 Geometrical Interface Gateway Q034
Show a menu: 1) Square, 2) Triangle. If the user picks 1, ask for a side length and print the square's area; if 2, ask for base and height and print the triangle's area; otherwise print "Invalid option selected". Example: 1, side 4 β Area: 16.0
print("1) Square\n2) Triangle\n")
choice = input("Enter option: ")
if choice == "1":
side = float(input("Side length: "))
print("Area:", side * side)
elif choice == "2":
base = float(input("Base: "))
h = float(input("Height: "))
print("Area:", 0.5 * base * h)
else:
print("Invalid option selected")
How it works: choice stays a string β compare it with "1" and "2" (text), not 1 and 2 (numbers).
Builds on Section 4 β review the lesson if you get stuck.
Module 5 β Count-Controlled Loops
Days 35β44 Β· Questions 035β044. Repeating a fixed number of times with for loops. Builds on Lesson 6.
Day 35 β Fixed Loop Iterator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 35 Fixed Loop Iterator Q035
Ask for a name and print it 3 times, one per line. Example: Alice β Alice, Alice, Alice
name = input("Name: ")
for i in range(3):
print(name)
How it works: for i in range(3) repeats the indented block exactly 3 times.
Day 36 β Variable Bound Iterator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 36 Variable Bound Iterator Q036
Ask for a name and a number, then print the name that many times. Example: Alice, 4 β Alice printed 4 times
name = input("Name: ")
num = int(input("Repetitions: "))
for i in range(num):
print(name)
How it works: range(num) uses a variable as its limit β the user decides how many times the loop runs.
Day 37 β Vertical Array Deconstructor
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 37 Vertical Array Deconstructor Q037
Ask for a name and print it one letter per line. Example: Bob β B, o, b
name = input("Name: ")
for char in name:
print(char)
How it works: A for loop can walk through a string one character at a time β no range() needed.
Day 38 β Nested Loop Matrix Printer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 38 Nested Loop Matrix Printer Q038
Ask for a name and a number. Print the name one letter per line, and repeat the whole thing that many times. Example: Bob, 2 β B, o, b, B, o, b
name = input("Name: ")
num = int(input("Times: "))
for i in range(num):
for char in name:
print(char)
How it works: A loop inside a loop: the inner loop finishes completely for every single run of the outer loop.
Day 39 β Times Table Multiplier Indexer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 39 Times Table Multiplier Indexer Q039
Ask for a number from 1 to 12 and print its times table from 1 to 12. Example: 5 β 1 x 5 = 5, 2 x 5 = 10, ... 12 x 5 = 60
num = int(input("Enter table multiplier (1-12): "))
for i in range(1, 13):
print(f"{i} x {num} = {i * num}")
How it works: range(1, 13) gives 1 to 12, and the loop variable i is used inside the calculation.
Day 40 β Dynamic Inverse Step Countdown
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 40 Dynamic Inverse Step Countdown Q040
Ask for a number below 50, then count down from 50 to that number. Example: 47 β 50, 49, 48, 47
target = int(input("Enter limit below 50: "))
for i in range(50, target - 1, -1):
print(i)
How it works: range(50, target - 1, -1) counts backwards β the step of -1 makes it decrease, and target - 1 makes the target itself included.
Day 41 β Guarded Dynamic Execution Gate
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 41 Guarded Dynamic Execution Gate Q041
Ask for a name and a number. If the number is less than 10, print the name that many times; otherwise print "Too high" 3 times. Example: Alice, 12 β Too high printed 3 times
name = input("Name: ")
num = int(input("Frequency value: "))
if num < 10:
for i in range(num):
print(name)
else:
for i in range(3):
print("Too high")
How it works: An if around a loop is a guard β it decides whether the loop runs at all.
Day 42 β Selective Value Accumulator Loop
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 42 Selective Value Accumulator Loop Q042
Ask for 5 numbers. After each one, ask "Include? (y/n)" β only add it to the total if the answer is y. Print the final total. Example: 10 (y), 5 (n), 7 (y) β Accumulated total: 17
total = 0
for i in range(5):
n = int(input("Enter value: "))
choice = input("Include? (y/n): ").lower()
if choice == "y":
total += n
print("Accumulated total:", total)
How it works: total += n adds to a running total β but only inside the if, so skipped numbers never count.
Day 43 β Direction-Selectable Loop Suite
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 43 Direction-Selectable Loop Suite Q043
Ask whether to count up or down. If up, ask for a top number and count 1 up to it; if down, ask for a floor below 20 and count down from 20 to it; otherwise print "I don't understand". Example: up, 3 β 1, 2, 3
mode = input("Count direction? (up/down): ").lower()
if mode == "up":
top = int(input("Target top limit: "))
for i in range(1, top + 1):
print(i)
elif mode == "down":
low = int(input("Target floor limit below 20: "))
for i in range(20, low - 1, -1):
print(i)
else:
print("I don't understand")
How it works: The mode chooses which loop runs β if/elif/else picks one branch, and each branch has its own range().
Day 44 β Registry Capacity Sentry Gate
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 44 Registry Capacity Sentry Gate Q044
Ask how many people are invited. If fewer than 10, ask for each guest's name and print "[name] has been invited"; otherwise print "Too many people". Example: 2 guests β Alice has been invited, Bob has been invited
guests = int(input("How many invitees? "))
if guests < 10:
for i in range(guests):
name = input("Guest name: ")
print(f"{name} has been invited")
else:
print("Too many people")
How it works: The if checks the size first β the loop only runs when the number is safe.
Builds on Section 6 β review the lesson if you get stuck.
Module 6 β Condition-Controlled Loops
Days 45β51 Β· Questions 045β051. Repeating until a condition changes, with while loops. Builds on Lesson 6.
Day 45 β Continuous Stack Accumulator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 45 Continuous Stack Accumulator Q045
Keep asking for numbers and adding them to a total. Stop when the total goes over 50, printing the total after each number. Example: 20, 20, 20 β The total is... 20, 40, 60
total = 0
while total <= 50:
num = int(input("Add number: "))
total += num
print("The total is...", total)
How it works: A while loop repeats while its condition is True β here the condition is total <= 50, so it stops as soon as the total passes 50.
Day 46 β Intercept Target Loop
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 46 Intercept Target Loop Q046
Keep asking for a number until the user enters a number over 5, then print the last number entered. Example: 2, 4, 7 β The last number you entered was a 7
num = 0
while num <= 5:
num = int(input("Enter number: "))
print(f"The last number you entered was a {num}")
How it works: The loop variable starts at 0 so the loop runs at least once; the condition is checked before each repeat.
Day 47 β Flag-Controlled Accumulator Array
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 47 Flag-Controlled Accumulator Array Q047
Ask for two numbers and add them. Then keep asking "Add another? (y/n)" β while the answer is y, ask for another number and add it. Print the total. Example: 5, 3, y, 4, n β Total: 12
n1 = int(input("Num 1: "))
n2 = int(input("Num 2: "))
total = n1 + n2
choice = input("Add another? (y/n): ").lower()
while choice == "y":
next_num = int(input("Next value: "))
total += next_num
choice = input("Add another? (y/n): ").lower()
print("Total:", total)
How it works: The answer "y" is a flag that controls the loop β it is set before the loop and updated at the end of each repeat.
Day 48 β Guest Tracker Registry Loop
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 48 Guest Tracker Registry Loop Q048
Keep inviting guests: ask for a name, print "[name] has now been invited", and ask if they want to invite another. When they say no, print how many are coming. Example: Alice (y), Bob (n) β Total attendees coming: 2
count = 0
choice = "y"
while choice == "y":
name = input("Invite name: ")
print(f"{name} has now been invited")
count += 1
choice = input("Invite another? (y/n): ").lower()
print("Total attendees coming:", count)
How it works: choice starts as "y" so the loop runs the first time, and count += 1 tracks how many guests were added.
Day 49 β High-Low Attempt Counter Matrix
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 49 High-Low Attempt Counter Matrix Q049
Guess the number 50. After each guess print "Too low" or "Too high", and count your attempts. When you guess right, print how many attempts you took. Example: 30, 60, 50 β Well done, you took 3 attempts
compnum = 50
guess = 0
attempts = 0
while guess != compnum:
guess = int(input("Guess value: "))
attempts += 1
if guess < compnum:
print("Too low")
elif guess > compnum:
print("Too high")
print(f"Well done, you took {attempts} attempts")
How it works: while guess != compnum keeps looping until the guess matches β attempts += 1 counts every try.
Day 50 β Forced Enclosure Range Trap
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 50 Forced Enclosure Range Trap Q050
Keep asking for a number between 10 and 20 until the user enters one inside the range. Print "Too low" or "Too high" after each wrong answer, then "Thank you". Example: 5, 25, 15 β Too low, Too high, Thank you
value = 0
while value < 10 or value > 20:
value = int(input("Enter number between 10 and 20: "))
if value < 10:
print("Too low")
elif value > 20:
print("Too high")
print("Thank you")
How it works: or joins the two bad cases β value < 10 or value > 20 β so the loop traps the user until the input is valid.
Day 51 β Interactive Song Loop Interface
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 51 Interactive Song Loop Interface Q051
Sing "10 green bottles": while bottles remain, print how many there are and ask how many will be left. If the answer is one less, take a bottle away; otherwise say "No, try again". When none are left, print "No more green bottles left".
bottles = 10
while bottles > 0:
print(f"There are {bottles} green bottles...")
ans = int(input("How many will be left? "))
if ans == bottles - 1:
bottles -= 1
print(f"Correct, there are {bottles} left")
else:
print("No, try again")
print("No more green bottles left")
How it works: bottles -= 1 only runs when the answer is right β wrong answers leave the count unchanged, so the loop keeps asking.
Builds on Section 6 β review the lesson if you get stuck.
Module 7 β Data Structures
Days 52β69 Β· Questions 052β069. Lists, 2D lists, tuples and dictionaries. Builds on Lessons 8β9.
Day 52 β Index Locator Query
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 52 Index Locator Query Q052
Show the list ["Myanmar", "Thailand", "Japan", "Singapore"]. Ask the user to type a country from the list and print its position index. Example: Japan β Position index: 2
countries = ["Myanmar", "Thailand", "Japan", "Singapore"]
print(countries)
query = input("Type a country from the list: ")
print("Position index:", countries.index(query))
How it works: .index(value) returns the position of a value in a list β the first item is at index 0.
Day 53 β Dynamic End Append Queue
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 53 Dynamic End Append Queue Q053
Start with ["Myanmar", "Thailand", "Japan"]. Ask for a new country, add it to the end of the list, and print the list. Example: add Vietnam β ["Myanmar", "Thailand", "Japan", "Vietnam"]
countries = ["Myanmar", "Thailand", "Japan"]
new_c = input("Add new country: ")
countries.append(new_c)
print(countries)
How it works: .append() adds one item to the end of a list.
Day 54 β Absolute Index Spatial Insert
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 54 Absolute Index Spatial Insert Q054
Start with ["Myanmar", "Thailand", "Japan"]. Ask for an index (0β2) and a country name, insert the country at that position, and print the list. Example: index 1, Vietnam β ["Myanmar", "Vietnam", "Thailand", "Japan"]
countries = ["Myanmar", "Thailand", "Japan"]
pos = int(input("Insert index position (0-2): "))
name = input("Country name: ")
countries.insert(pos, name)
print(countries)
How it works: .insert(pos, value) puts an item at an exact position and shifts the rest along.
Day 55 β Element Name Destructive Purge
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 55 Element Name Destructive Purge Q055
Show the subjects ["CS", "Maths", "Physics", "Chemistry"]. Ask which one the user dislikes, remove it, and print what is left. Example: dislike Maths β Remaining queue: ["CS", "Physics", "Chemistry"]
subs = ["CS", "Maths", "Physics", "Chemistry"]
bad = input(f"Options: {subs}. What do you dislike? ")
subs.remove(bad)
print("Remaining queue:", subs)
How it works: .remove(value) deletes the first item with that value from the list.
Day 56 β Alphabetic Array Sorting Engine
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 56 Alphabetic Array Sorting Engine Q056
Start with ["Laphet", "Mohinga", "Pizza"]. Ask the user to add a food, then sort the list alphabetically and print it. Example: add Burger β ["Burger", "Laphet", "Mohinga", "Pizza"]
foods = ["Laphet", "Mohinga", "Pizza"]
foods.append(input("Add food: "))
foods.sort()
print(foods)
How it works: .sort() rearranges a list in place β alphabetically for strings.
Day 57 β Guarded Element Purge Engine
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 57 Guarded Element Purge Engine Q057
Start with ["CPU", "RAM", "SSD", "GPU"]. Ask for a component: if it is in the list, remove it; otherwise print "Item not found". Print the list either way. Example: RAM β ["CPU", "SSD", "GPU"]
comps = ["CPU", "RAM", "SSD", "GPU"]
item = input("Component: ")
if item in comps:
comps.remove(item)
else:
print("Item not found")
print(comps)
How it works: Check with "in" BEFORE removing β .remove() crashes with ValueError if the item is not there.
Day 58 β 2D Nested Array Matrix Reader
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 58 2D Nested Array Matrix Reader Q058
A 2D list holds names and ages: [["Sara", 14], ["Alex", 16], ["John", 15]]. Ask for a row number (0β2) and print that whole row. Example: row 1 β ["Alex", 16]
matrix = [["Sara", 14], ["Alex", 16], ["John", 15]]
row = int(input("Row entry (0-2): "))
print(matrix[row])
How it works: matrix[row] picks one inner list β a 2D list is a list of lists.
Day 59 β 2D Relational Matrix Search Engine
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 59 2D Relational Matrix Search Engine Q059
Using the same 2D list, ask for a name and print that person's age. If the name is not there, print "Record missing". Example: Alex β Age match is 16
matrix = [["Sara", 14], ["Alex", 16], ["John", 15]]
name = input("Target name query: ")
found = False
for row in matrix:
if row[0] == name:
print(f"Age match is {row[1]}")
found = True
if not found:
print("Record missing")
How it works: Loop through the rows and compare row[0] with the name β a flag (found) records whether any row matched.
Day 60 β Dictionary Key Resolution Map
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 60 Dictionary Key Resolution Map Q060
A dictionary maps ICT words to meanings. Print the keys, ask the user to pick one, and print its meaning β or "Key missing" if it is not there. Example: RAM β Volatile memory
glossary = {"RAM": "Volatile memory", "CPU": "Processing unit", "SSD": "Storage"}
print(glossary.keys())
query = input("Select key: ")
print(glossary.get(query, "Key missing"))
How it works: .get(key, default) reads a value safely β it returns the default instead of crashing when the key is missing.
Day 61 β Guarded Dictionary Map Extension
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 61 Guarded Dictionary Map Extension Q061
A glossary dictionary already has RAM and CPU. Ask for a word: if it exists, print "Key assignment block! Record exists."; otherwise ask for its definition and add it. Print the dictionary.
glossary = {"RAM": "Volatile memory", "CPU": "Processing unit"}
word = input("Enter keyword: ")
if word in glossary:
print("Key assignment block! Record exists.")
else:
definition = input("Enter definition: ")
glossary[word] = definition
print(glossary)
How it works: glossary[word] = definition adds a new key-value pair β or overwrites the value if the key already exists.
Day 62 β Index-Matched Value Swapper
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 62 Index-Matched Value Swapper Q062
IDs are [101, 102, 103, 104, 105]. Ask for an ID to change: if it is in the list, find its index and replace it with a new value. Print the list. Example: change 103 to 999 β [101, 102, 999, 104, 105]
ids = [101, 102, 103, 104, 105]
target = int(input("ID to alter: "))
if target in ids:
idx = ids.index(target)
ids[idx] = int(input("New ID value: "))
print(ids)
How it works: .index(value) finds WHERE an item is, then ids[idx] = new_value replaces it.
Day 63 β Flag Driven List Builder Queue
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 63 Flag Driven List Builder Queue Q063
Ask for three names and store them in a list. Then keep asking "Add alternative name? (yes/no)" β while the answer is not "no", keep adding names. Print how many names there are. Example: Alice, Bob, Carol, yes, Dave, no β Count metrics: 4
names = [input("Name 1: "), input("Name 2: "), input("Name 3: ")]
flag = input("Add alternative name? (yes/no): ").lower()
while flag != "no":
names.append(input("Enter name: "))
flag = input("Add alternative name? (yes/no): ").lower()
print("Count metrics:", len(names))
How it works: The while condition is flag != "no" β any answer except "no" keeps the loop going.
Day 64 β Frequency Analysis Loop Counter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 64 Frequency Analysis Loop Counter Q064
The list [2, 5, 3, 5, 7] is given. Ask for a value and print how many times it appears. Example: 5 β Occurrences total: 2
nums = [2, 5, 3, 5, 7]
query = int(input("Count matches for value: "))
print("Occurrences total:", nums.count(query))
How it works: .count(value) returns how many times a value appears in a list.
Day 65 β Linear Character String Scanner
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 65 Linear Character String Scanner Q065
Ask for some text and count how many vowels (a, e, i, o, u) it contains. Example: "Hello World" β Total vowels counted: 3
text = input("Provide string payload: ").lower()
vowels = "aeiou"
count = 0
for char in text:
if char in vowels:
count += 1
print("Total vowels counted:", count)
How it works: Loop through each character and test "if char in vowels" β the counter only increases for vowels.
Day 66 β Immutable Constant Array Reference
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 66 Immutable Constant Array Reference Q066
The days of the week are stored as a tuple ("Mon", "Tue", "Wed", "Thu", "Fri"). Ask for a number 1β5 and print that day. Example: 3 β Wed
days = ("Mon", "Tue", "Wed", "Thu", "Fri")
idx = int(input("Select layout index (1-5): "))
print(days[idx - 1])
How it works: A tuple works like a list for reading, but it cannot be changed β and days[idx - 1] converts the user's 1β5 choice to a 0β4 index.
Day 67 β Lookup Intercept Entry Manager
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 67 Lookup Intercept Entry Manager Q067
The list [45, 22, 89, 12] is given. Ask for a number: if it is in the list, print its index; otherwise add it to the list and print the list. Example: 22 β Index reference location: 1; 50 β [45, 22, 89, 12, 50]
items = [45, 22, 89, 12]
num = int(input("Value query: "))
if num in items:
print("Index reference location:", items.index(num))
else:
items.append(num)
print(items)
How it works: "in" decides the branch β find the index if the value exists, append it if it does not.
Day 68 β Multi-Level 2D Database Query System
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 68 Multi-Level 2D Database Query System Q068
A dictionary stores students and their marks: {"Lin": {"Math": 85, "CS": 90}, "Htet": {"Math": 70, "CS": 80}}. Ask for a student name and print their average mark, or "Student record untraceable" if the name is not there. Example: Lin β Average grade balance: 87.5
db = {"Lin": {"Math": 85, "CS": 90}, "Htet": {"Math": 70, "CS": 80}}
name = input("Student name: ")
if name in db:
marks = db[name].values()
print("Average grade balance:", sum(marks) / len(marks))
else:
print("Student record untraceable")
How it works: db[name] is itself a dictionary β .values() gives its marks, and sum() / len() gives the average.
Day 69 β Manual Aggregate Analytics Pipeline
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 69 Manual Aggregate Analytics Pipeline Q069
Ask for 5 numbers, store them in a list, then print their sum, the highest and the lowest β without using sum(), min() or max(). Example: 4, 9, 2, 7, 5 β Sum: 27, High: 9, Low: 2
nums = []
for i in range(5):
nums.append(int(input(f"Value {i+1}: ")))
s_val = nums[0]
h_val = nums[0]
total = 0
for x in nums:
total += x
if x < s_val: s_val = x
if x > h_val: h_val = x
print(f"Sum: {total}, High: {h_val}, Low: {s_val}")
How it works: Start smallest and largest at the first number, then update them inside the loop whenever a bigger or smaller value appears.
Builds on Sections 8β9 β review the lesson if you get stuck.
Module 8 β File Handling
Days 70β85 Β· Questions 070β085. Reading and writing files: text files and CSV files.
Day 70 β Destructive Outstream File Generator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 70 Destructive Outstream File Generator Q070
Write three names (Wai Lin, Htet, Kyaw) into a new file called Names.txt β one name per line. (This overwrites the file if it already exists.)
with open("Names.txt", "w") as file:
file.write("Wai Lin\nHtet\nKyaw\n")
How it works: open("Names.txt", "w") creates or overwrites the file, and \n inside the string puts each name on its own line.
Day 71 β Safe Instream File Reader
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 71 Safe Instream File Reader Q071
Read the file Names.txt and print everything in it.
with open("Names.txt", "r") as file:
print(file.read())
How it works: open("Names.txt", "r") opens the file for reading, and .read() returns the whole contents as one string.
Day 72 β Non-Destructive Appender File Interface
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 72 Non-Destructive Appender File Interface Q072
Ask for a name, add it to the end of Names.txt, then read the file and print everything in it. Example: add "Thura" β the file now shows all four names
new_name = input("Add name item: ")
with open("Names.txt", "a") as file:
file.write(new_name + "\n")
with open("Names.txt", "r") as file:
print(file.read())
How it works: Mode "a" appends without erasing β "w" would have deleted the old names first.
Day 73 β Unified I/O Storage Terminal Switch
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 73 Unified I/O Storage Terminal Switch Q073
Show a menu: 1) Create, 2) Display, 3) Append. If the user picks 1, ask for a filename and content and create the file; 2 prints Names.txt; 3 adds a new line to Names.txt.
print("1) Create\n2) Display\n3) Append")
cmd = input("Command: ")
if cmd == "1":
f = input("Filename: ") + ".txt"
with open(f, "w") as file: file.write(input("Content: ") + "\n")
elif cmd == "2":
with open("Names.txt", "r") as file: print(file.read())
elif cmd == "3":
with open("Names.txt", "a") as file: file.write(input("New line: ") + "\n")
How it works: One menu, three file modes β "w" creates, "r" reads, "a" appends β chosen by the if/elif chain.
Day 74 β Parsed Numeric File Aggregator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 74 Parsed Numeric File Aggregator Q074
Read Numbers.txt (one number per line) and print the total of all the numbers. Example: file holds 10, 20, 30 β Calculated summation scale: 60
with open("Numbers.txt", "r") as file:
total = 0
for line in file:
total += int(line.strip())
print("Calculated summation scale:", total)
How it works: Loop through the file line by line, .strip() removes the newline, and int() converts each line to a number before adding it.
Day 75 β Structured Table CSV Writer Array
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 75 Structured Table CSV Writer Array Q075
Create a CSV file Books.csv with a header row (Title, Author, Year) and two book rows: Macbeth / Shakespeare / 1606 and Python CS / Tr. Htet / 2026.
import csv
with open("Books.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Title", "Author", "Year"])
writer.writerow(["Macbeth", "Shakespeare", "1606"])
writer.writerow(["Python CS", "Tr. Htet", "2026"])
How it works: csv.writer() writes rows as lists, and newline="" stops Python adding blank lines between rows.
Day 76 β Relational Grid Attribute Filter Query
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 76 Relational Grid Attribute Filter Query Q076
Ask for a year, then read Books.csv and print only the books published after that year. Example: after 1900 β the Python CS row
import csv
target_year = int(input("View books published after year: "))
with open("Books.csv", "r") as file:
reader = csv.reader(file)
next(reader) # Bypass headers array block
for row in reader:
if int(row[2]) > target_year:
print(row)
How it works: next(reader) skips the header row, and int(row[2]) reads the Year column (column index 2) as a number.
Day 77 β Transactional Memory Record Purger
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 77 Transactional Memory Record Purger Q077
Ask for a book title to erase. Read Books.csv, keep every row except that title, then write the kept rows back to the file.
import csv
target_title = input("Enter book title to erase: ")
rows_to_keep = []
with open("Books.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] != target_title: rows_to_keep.append(row)
with open("Books.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(rows_to_keep)
How it works: Read everything into a list first, filter out the unwanted row, then rewrite the whole file β you cannot delete one row in place.
Day 78 β Prefix Sequence Match Scanner
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 78 Prefix Sequence Match Scanner Q078
Ask for a letter, then read Names.txt and print only the names that start with that letter. Example: letter S β every name starting with S
prefix = input("Find names starting with letter: ").upper()
with open("Names.txt", "r") as file:
for line in file:
if line.upper().startswith(prefix):
print(line.strip())
How it works: .startswith(prefix) tests the start of a string β .upper() on both sides makes the match case-insensitive.
Day 79 β Long-Term Event Append Log Tracker
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 79 Long-Term Event Append Log Tracker Q079
Ask for a diary entry and append it to Diary.txt with today's date in front, like [2026-11-15] My entry.
import datetime
note = input("Type entry log payload: ")
with open("Diary.txt", "a") as file:
file.write(f"[{datetime.date.today()}] {note}\n")
How it works: datetime.date.today() gives today's date, and mode "a" adds the entry without erasing earlier ones.
Day 80 β Conditional Safety Sentry System
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 80 Conditional Safety Sentry System Q080
Read Inventory.csv (item, quantity) and print a warning for every item with fewer than 5 in stock. Example: Pens 3 β Exception: Item Pens low capacity profile: 3
import csv
print("--- Low Stock Exceptions Sentry ---")
with open("Inventory.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if int(row[1]) < 5:
print(f"Exception: Item {row[0]} low capacity profile: {row[1]}")
How it works: int(row[1]) reads the quantity column as a number so it can be compared with 5.
Day 81 β Buffer Synchronized File Registry Editor
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 81 Buffer Synchronized File Registry Editor Q081
Ask for a number to clean out of Numbers.txt. Read the file, keep every line except that number, and write the kept lines back.
target = input("Number value to clean: ").strip()
buffer = []
with open("Numbers.txt", "r") as file:
for line in file:
if line.strip() != target: buffer.append(line)
with open("Numbers.txt", "w") as file:
file.writelines(buffer)
How it works: Same read-filter-rewrite pattern as Day 77 β but compare line.strip() with the target so the newline does not get in the way.
Day 82 β Structural Word Metrics Profiler
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 82 Structural Word Metrics Profiler Q082
Read Story.txt and print how many words it contains.
with open("Story.txt", "r") as file:
payload = file.read()
tokens = payload.split()
print("Calculated words metric metric:", len(tokens))
How it works: .split() breaks the text into a list of words β len() of that list is the word count.
Day 83 β Pipeline Transformer Stream Mirror
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 83 Pipeline Transformer Stream Mirror Q083
Read Story.txt and write an UPPERCASE copy of it into Backup.txt.
with open("Story.txt", "r") as source, open("Backup.txt", "w") as dest:
for line in source:
dest.write(line.upper())
How it works: Open two files at once β one for reading, one for writing β and .upper() each line as you copy it.
Day 84 β Row-Level Database Value Modifier
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 84 Row-Level Database Value Modifier Q084
Ask for an item and a new quantity. Read Inventory.csv, change that item's quantity, and write all rows back. Example: change Pens to 10 β the Pens row now reads Pens,10
import csv
target_item = input("Item to modify: ")
new_qty = input("New value: ")
buffer = []
with open("Inventory.csv", "r") as file:
for row in csv.reader(file):
if row[0] == target_item: row[1] = new_qty
buffer.append(row)
with open("Inventory.csv", "w", newline="") as file:
csv.writer(file).writerows(buffer)
How it works: row[1] = new_qty edits the quantity in memory; rewriting the file saves the change.
Day 85 β Secure CSV Verification Control Gate
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 85 Secure CSV Verification Control Gate Q085
Ask for a username and a secret code. Check Logins.csv β if a row matches both, print "Access Granted"; otherwise print "Security Alert: Reject Access".
import csv
user = input("User profile: ")
passw = input("Secret code: ")
authenticated = False
with open("Logins.csv", "r") as file:
for row in csv.reader(file):
if row[0] == user and row[1] == passw:
authenticated = True
break
print("Access Granted" if authenticated else "Security Alert: Reject Access")
How it works: A flag (authenticated) starts False and flips to True only on a matching row β break stops the search as soon as a match is found.
Builds on Sections 8β9 β review the lesson if you get stuck.
Module 9 β Modular Subprogramming
Days 86β100 Β· Questions 086β100, plus 5 bonus challenges (101β105). Writing your own functions. Builds on Lesson 7.
Day 86 β Inter-Functional Pipeline Bridge
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 86 Inter-Functional Pipeline Bridge Q086
Write two functions: fetch_num() asks for a number and returns it, and scale_value(n) returns n Γ 10. Call one inside the other to print the scaled number. Example: input 7 β 70
def fetch_num():
return int(input("Enter raw number: "))
def scale_value(n):
return n * 10
# Call Stack invocation
print(scale_value(fetch_num()))
How it works: Functions can call each other β scale_value(fetch_num()) runs fetch_num() first and passes its result straight into scale_value().
Day 87 β Parametric Character Procedural Stream
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 87 Parametric Character Procedural Stream Q087
Write a function display_pattern(count) that prints that many stars in a row. Call it with 5. Example output: *****
def display_pattern(count):
print("*" * count)
display_pattern(5)
How it works: "*" * count repeats the character β a string times a number is that string repeated.
Day 88 β Max Value Comparator Evaluator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 88 Max Value Comparator Evaluator Q088
Write a function extract_max(a, b) that returns the bigger of two numbers. Ask for two numbers and print the bigger one. Example: A 4, B 9 β 9
def extract_max(a, b):
return a if a > b else b
print(extract_max(float(input("A: ")), float(input("B: "))))
How it works: return a if a > b else b is a one-line if β the function returns a value instead of printing it.
Day 89 β Parametric Circle Math Solver
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 89 Parametric Circle Math Solver Q089
Write a function compute_circle_area(r) that returns pi Γ r squared. Ask for a radius and print the area. Example: Radius 2 β about 12.57
import math
def compute_circle_area(r):
return math.pi * (r ** 2)
print(compute_circle_area(float(input("Radius: "))))
How it works: import math inside the program gives the function math.pi β the caller only passes the radius.
Day 90 β Boundary Constrained Generator Module
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 90 Boundary Constrained Generator Module Q090
Write a function generate_bound_rand(low, high) that returns a random whole number between low and high. Call it with 1 and 100 and print the result.
import random
def generate_bound_rand(low, high):
return random.randint(low, high)
print(generate_bound_rand(1, 100))
How it works: random.randint(low, high) includes BOTH ends β the result can be 1 or 100.
Day 91 β Array Reversing Slice Generator
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 91 Array Reversing Slice Generator Q091
Write a function invert_string(payload) that returns the string reversed. Ask for some text and print it backwards. Example: hello β olleh
def invert_string(payload):
return payload[::-1]
print(invert_string(input("Text to turn: ")))
How it works: payload[::-1] is a slice with a step of -1 β it walks the string backwards.
Day 92 β Boolean Attribute Match Verifier
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 92 Boolean Attribute Match Verifier Q092
Write a function verify_even(number) that returns True if the number is even, False if it is odd. Ask for a number and print the result. Example: 8 β Even state: True
def verify_even(number):
return number % 2 == 0
print("Even state:", verify_even(int(input("Query: "))))
How it works: number % 2 == 0 is True exactly when the number divides by 2 with no remainder.
Day 93 β Collection Summary Mean Computer
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 93 Collection Summary Mean Computer Q093
Write a function calculate_list_average(dataset) that returns the average of a list. Call it with [10, 20, 30, 40] and print the result. Example output: 25.0
def calculate_list_average(dataset):
return sum(dataset) / len(dataset)
print(calculate_list_average([10, 20, 30, 40]))
How it works: sum(dataset) / len(dataset) is the average β the function works for any list, not just this one.
Day 94 β Architecture Standard Calculator Console
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 94 Architecture Standard Calculator Console Q094
Build a calculator: four small functions add, sub, mul and div (div returns "Violation" when dividing by zero), plus a terminal() function that shows a menu, asks for two numbers, and calls the right function. Run terminal(). Example: 1, 6, 3 β 9
def add(x,y): return x+y
def sub(x,y): return x-y
def mul(x,y): return x*y
def div(x,y): return x/y if y!=0 else "Violation"
def terminal():
print("1.Add 2.Sub 3.Mul 4.Div")
cmd = input("Select: ")
a, b = float(input("Arg 1: ")), float(input("Arg 2: "))
if cmd=="1": print(add(a,b))
elif cmd=="2": print(sub(a,b))
elif cmd=="3": print(mul(a,b))
elif cmd=="4": print(div(a,b))
terminal()
How it works: Small functions do one job each; terminal() is the interface that asks the user and routes to the right function β this is modular design.
Day 95 β Structural Password Sentry Verifier
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 95 Structural Password Sentry Verifier Q095
Write a function enforce_password_criteria(text) that returns True only if the password is at least 8 characters long AND contains a digit. Ask for a password and print whether it is valid. Example: abc12345 β Valid profile: True
def enforce_password_criteria(text):
if len(text) < 8: return False
return any(c.isdigit() for c in text)
print("Valid profile:", enforce_password_criteria(input("Password: ")))
How it works: any(c.isdigit() for c in text) is True when at least one character is a digit.
Day 96 β Two-Way Conversion Metric Manager
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 96 Two-Way Conversion Metric Manager Q096
Write two functions: kg_to_lbs(kg) returns kg Γ 2.204, and lbs_to_kg(lbs) returns lbs Γ· 2.204. (These are the conversion tools β later programs will call them.)
def kg_to_lbs(kg): return kg * 2.204 def lbs_to_kg(lbs): return lbs / 2.204 # Interface modules route arguments to matching operations
How it works: Two small functions, one job each β the caller chooses which conversion to use. This is the same pair of conversions from Day 10, now as reusable functions.
Day 97 β Exam Grade Boundary Mapper
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 97 Exam Grade Boundary Mapper Q097
Write a function map_grade(score) that returns "A*" for 90+, "A" for 80+, "B" for 70+, and "Ungraded" otherwise. Ask for a score and print the grade. Example: 85 β Syllabus rank: A
def map_grade(score):
if score >= 90: return "A*"
elif score >= 80: return "A"
elif score >= 70: return "B"
return "Ungraded"
print("Syllabus rank:", map_grade(int(input("Score: "))))
How it works: Return early from each branch β the first matching return wins, so the checks must go from highest to lowest.
Day 98 β Reference In-Place List Modifier
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 98 Reference In-Place List Modifier Q098
Write a function apply_discount(prices) that returns a new list with 10% off every price, rounded to 2 decimal places. Call it with [100.0, 50.0, 25.0] and print the result. Example output: [90.0, 45.0, 22.5]
def apply_discount(prices):
return [round(x * 0.9, 2) for x in prices]
print(apply_discount([100.0, 50.0, 25.0]))
How it works: A list comprehension [round(x * 0.9, 2) for x in prices] builds the new list in one line β the original list is unchanged.
Day 99 β Exception Guarded Line Counter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 99 Exception Guarded Line Counter Q099
Write a function count_file_lines(filename) that returns how many lines the file has β or -1 if the file does not exist. Call it with "Names.txt" and print the result.
import os
def count_file_lines(filename):
if not os.path.exists(filename): return -1
with open(filename, "r") as file: return len(file.readlines())
print(count_file_lines("Names.txt"))
How it works: os.path.exists() checks first, so the function never crashes on a missing file β returning -1 signals "not found".
Day 100 β Math Factorial Processor Loop
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Day 100 Math Factorial Processor Loop Q100
Write a function compute_factorial(n) that returns n! (n Γ (n-1) Γ ... Γ 1). Call it with 5 and print the result. Example output: 120
def compute_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(compute_factorial(5))
How it works: Start result at 1 and multiply it by every number from 1 to n β the loop does the repeated work.
Bonus 1 β Palindrome Sequence Match Checker
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Bonus 1 Palindrome Sequence Match Checker Q101
Write a function test_palindrome(word) that returns True if the word reads the same forwards and backwards (ignoring case and spaces at the ends). Ask for a word and print the result. Example: madam β Symmetric match: True
def test_palindrome(word):
clean = word.lower().strip()
return clean == clean[::-1]
print("Symmetric match:", test_palindrome(input("Word: ")))
How it works: Clean the word first (.lower() and .strip()), then compare it with its reverse β clean == clean[::-1].
Bonus 2 β Structured Quiz Architecture Suite
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Bonus 2 Structured Quiz Architecture Suite Q102
Build a small quiz: load_db() returns a dictionary of questions and answers, and run_quiz() asks each question, counts correct answers, and prints the final score. Run the quiz. Example: 1+1 β 2, Cap of MM? β Naypyidaw
def load_db(): return {"1+1": "2", "Cap of MM?": "Naypyidaw"}
def run_quiz():
db = load_db(); score = 0
for q, a in db.items():
if input(q + ": ") == a: score += 1
print(f"Final Score: {score}/{len(db)}")
run_quiz()
How it works: db.items() gives each question-answer pair in turn β the score only increases when the answer matches exactly.
Bonus 3 β Array Mapping String Splitter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Bonus 3 Array Mapping String Splitter Q103
Write a function profile_word_lengths(sentence) that returns a list of the length of each word. Call it with "Python Computer Science Guide" and print the result. Example output: [6, 8, 7, 5]
def profile_word_lengths(sentence):
return [len(w) for w in sentence.split()]
print(profile_word_lengths("Python Computer Science Guide"))
How it works: sentence.split() gives the words, and [len(w) for w in ...] maps each word to its length.
Bonus 4 β Array Collision Intersection Filter
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Bonus 4 Array Collision Intersection Filter Q104
Write a function extract_intersection(l1, l2) that returns the values found in BOTH lists. Call it with [1, 2, 3] and [2, 3, 4] and print the result. Example output: [2, 3]
def extract_intersection(l1, l2):
return list(set(l1) & set(l2))
print(extract_intersection([1,2,3], [2,3,4]))
How it works: set(l1) & set(l2) is the intersection β converting back to a list gives the shared values (order may vary).
Bonus 5 β Guarded State Transaction Manager
This exercise is for approved SrWL Learning students. Sign in with Google to unlock it β Day 1 is free to try now.
Bonus 5 Guarded State Transaction Manager Q105
A bank account starts with balance 1000.0. Write deposit(amt) and withdraw(amt) functions that update the shared balance β withdraw returns "Insufficient funds" if the amount is more than the balance. Withdraw 250.0 and print the remaining balance. Example output: Remaining transaction ledger balance: 750.0
balance = 1000.0
def deposit(amt): global balance; balance += amt; return balance
def withdraw(amt):
global balance
if amt > balance: return "Insufficient funds"
balance -= amt; return balance
print("Remaining transaction ledger balance:", withdraw(250.0))
How it works: global balance lets a function change the variable outside it β without "global", the assignment would create a new local variable instead.
Builds on Section 7 β review the lesson if you get stuck.