Week 2: Strings in Depth, Decisions (if/elif/else) and Loops
Month 1 | Main goal: The student can process text, make decisions with
if, and repeat work withwhile/for— and build the "Bahatisha Namba" (Guess the Number) game.
Teacher Preparation (read before the week starts)
- There is nothing new to install. Create the folder
python_darasa\wiki02. - Read: https://docs.python.org/3/tutorial/introduction.html#text (strings) and https://docs.python.org/3/tutorial/controlflow.html (if, for, range, break, continue).
- Practise yourself: write the "Bahatisha Namba" game (Session 3) on your own before Session 3. If you can write it without looking, you will teach it with confidence.
- The most important thing this week: INDENTATION. Python uses 4 spaces at the start of a line to show code that is "inside" an
if,whileorfor. VS Code inserts 4 spaces when you press Tab. Make sure the bottom right corner of VS Code says "Spaces: 4". - Know how to stop a stuck program (an infinite loop): press
Ctrl + Cin the terminal. You will need it!
Week Goals (by the end of the week the student will be able to...)
- Use indexing (
s[0],s[-1]) and slicing (s[1:4],s[::-1]) on strings. - Use string methods:
upper,lower,title,strip,replace,split,find,count,startswith,isdigit, as well aslen()andin. - Use f-strings:
f"Habari {jina}",f"{bei:,.2f}". - Write decisions with
if / elif / elseand nested conditions. - Repeat work with
whileandfor, and userange(),break,continue. - Use
random.randint()to build a number-guessing game.
Session 1 — Strings in Depth: indexing, slicing, methods, f-strings
Session flow
- Homework review (kibadilishaji.py)
- A string is a sequence of characters:
len(), indexing, negative index - Slicing
[start:stop:step] - Break
- String methods
- f-strings and number formatting
- In-class exercise
- Q&A + homework
Explanation for the teacher (read this first)
-
A string is a sequence of characters. Each character has a position number called an index, and the index starts at 0, not 1.
T a n z a n i a 0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1
-
s[0]→ the first character;s[-1]→ the last character.len(s)→ the number of characters (8). An index greater thanlen(s)-1→IndexError. - Slicing
s[start:stop]takes fromstartup to but not includingstop.s[0:3]→"Tan". Leave outstart→ from the beginning; leave outstop→ to the end.s[::2]→ every second character.s[::-1]→ the reversed string. - Slicing doesn't raise
IndexErroreven if you go too far:s[0:100]→ the whole string. - Strings cannot be changed (immutable):
s[0] = "t"→TypeError. Methods don't change the original string; they return a new string. That's why we writejina = jina.upper(). - Important methods:
.upper(),.lower(),.title(),.capitalize(),.strip()(removes spaces at the edges),.replace(a, b),.split()(splits into a list — we will see more of it in Week 3),.find(x)(the index or -1),.count(x),.startswith(x),.endswith(x),.isdigit(),.isalpha()."x" in s→ True/False. - f-string: put
fbefore the quote, then put variables inside{}:f"Jina: {jina}, umri: {umri}". You can include calculations:f"{a + b}". Formatting:{x:.2f}→ 2 decimals;{x:,}→ thousands commas;{x:,.2f}→ both;{jina:>10}→ align right in width 10;{jina:<10}left;{jina:^10}centre.
Say this to the student
- "A string is like a train with carriages. Each carriage holds one character, and the carriages are numbered starting from 0. You can call the last carriage -1."
- "Slicing is like cutting a piece of bread:
[2:5]means 'start cutting at mark 2, stop before mark 5'." - "A string cannot be changed — it is like words carved into stone. If you want something different, you carve a new stone."
- "An f-string is like a form with blank spaces
{}— Python fills those spaces with the values of variables."
Type this code live (share screen)
Step 1 — strings.py: indexing and len
nchi = "Tanzania" print(len(nchi)) # 8 print(nchi[0]) # T print(nchi[1]) # a print(nchi[-1]) # a print(nchi[-2]) # i print(nchi[len(nchi) - 1]) # a (herufi ya mwisho kwa njia ndefu)
Step 2 — Slicing
nchi = "Tanzania" print(nchi[0:3]) # Tan print(nchi[3:]) # zania print(nchi[:5]) # Tanza print(nchi[-3:]) # nia print(nchi[::2]) # Tnai print(nchi[::-1]) # ainaznaT print(nchi[0:100]) # Tanzania (hakuna error)
Step 3 — Methods
ujumbe = " habari ya asubuhi, mwalimu " print(ujumbe.strip()) # habari ya asubuhi, mwalimu print(ujumbe.strip().upper()) # HABARI YA ASUBUHI, MWALIMU print(ujumbe.strip().title()) # Habari Ya Asubuhi, Mwalimu print(ujumbe.replace("asubuhi", "jioni").strip()) # habari ya jioni, mwalimu print(ujumbe.count("a")) # 5 print(ujumbe.find("mwalimu")) # 22 print(ujumbe.find("Dodoma")) # -1 (haipo) print("habari" in ujumbe) # True print(ujumbe) # haijabadilika! bado ina nafasi
Emphasise the last line: methods don't change the original string.
simu = "0712345678" print(simu.isdigit()) # True print(simu.startswith("07")) # True print("Amina".isalpha()) # True print("Amina 2".isalpha()) # False (nafasi na namba) sentensi = "Python ni rahisi sana" maneno = sentensi.split() print(maneno) # ['Python', 'ni', 'rahisi', 'sana'] print(len(maneno)) # 4
Step 4 — f-strings
jina = "Juma" umri = 22 bei = 1234567.891 print(f"Jina langu ni {jina} na nina miaka {umri}.") print(f"Mwaka ujao: {umri + 1}") print(f"Jina kwa herufi kubwa: {jina.upper()}") print(f"Bei: {bei:.2f}") print(f"Bei: {bei:,.2f} TZS") print(f"[{jina:<10}]") print(f"[{jina:>10}]") print(f"[{jina:^10}]")
Output:
Jina langu ni Juma na nina miaka 22. Mwaka ujao: 23 Jina kwa herufi kubwa: JUMA Bei: 1234567.89 Bei: 1,234,567.89 TZS [Juma ] [ Juma] [ Juma ]
Step 5 — Real example: cleaning up a user's name
jina = input("Andika jina lako: ") jina_safi = jina.strip().title() print(f"Karibu {jina_safi}! Jina lako lina herufi {len(jina_safi)}.") print(f"Herufi ya kwanza: {jina_safi[0]}, ya mwisho: {jina_safi[-1]}") print(f"Jina lako kinyume: {jina_safi[::-1]}")
Andika jina lako: neema Karibu Neema! Jina lako lina herufi 5. Herufi ya kwanza: N, ya mwisho: a Jina lako kinyume: ameeN
Questions to ask the student
"Python"[2]? — Answer:"t"."Python"[-1]? — Answer:"n"."Python"[1:4]? — Answer:"yth"(index 1, 2, 3).- After
s = "abc"; s.upper(), what iss? — Answer: still"abc"; you must writes = s.upper(). - How would you reverse a string? — Answer:
s[::-1]. "ana" in "Tanzania"? — Answer:False. T-a-n-z-a-n-i-a contains "an" but there is no "a-n-a" in a row."zan" in "Tanzania"isTrue. Confirm it together in the REPL.
Common mistakes
| Mistake | Error message | Fix |
|---|---|---|
| Index out of range | IndexError: string index out of range |
The last index is len(s) - 1, or use -1. |
| Changing a single character | TypeError: 'str' object does not support item assignment |
Create a new string: s = "t" + s[1:]. |
| Forgetting a method's parentheses | print(s.upper) → <built-in method upper of str object at 0x...> |
s.upper() |
Forgetting the f |
print("Habari {jina}") → displays {jina} as it is |
print(f"Habari {jina}") |
| Thinking a method changes the string | The string doesn't change | s = s.strip() |
| Using index 1 for the first character | You get the second character | The index starts at 0. |
In-class exercise
- Ask for a full name (e.g. "amina juma hassan"). Display: the name with
title(), the initials (A.J.H.), and the number of letters without spaces. - Ask for a word; display whether it is a palindrome (reads the same backwards, e.g. "kayak", "ada") —
True/False. - Ask for a phone number; display
Trueif it has 10 characters, all digits, and starts with "0".
Answer
# zoezi 1 jina = input("Jina kamili: ").strip() maneno = jina.title().split() print("Jina:", jina.title()) initials = maneno[0][0] + "." + maneno[1][0] + "." + maneno[2][0] + "." print("Initials:", initials) print("Herufi bila nafasi:", len(jina.replace(" ", ""))) # Kumbuka: hii inafanya kazi kwa majina 3 tu; Wiki 2 Kipindi 3 (for loop) tutaifanya ya jumla.
# zoezi 2 neno = input("Neno: ").strip().lower() print("Ni palindrome?", neno == neno[::-1])
# zoezi 3 simu = input("Namba ya simu: ").strip() sahihi = len(simu) == 10 and simu.isdigit() and simu.startswith("0") print("Namba sahihi?", sahihi)
Session 2 — Decisions: if / elif / else and Nested Conditions
Session flow
- Homework review
ifalone, indentation,elseelif— multiple choices (example: grade bands for marks)- Break
- Nested conditions + combining with
and/or - Big example: transport fare calculator / simple ATM
- In-class exercise
- Q&A + homework
Explanation for the teacher (read this first)
if sharti:(sharti= condition) — if the condition isTrue, Python runs the indented lines below it. If it isFalse, it skips them.-
Structure:
if sharti_1: # inafanyika kama sharti_1 ni True elif sharti_2: # inafanyika kama sharti_1 ni False NA sharti_2 ni True else: # inafanyika kama yote juu ni False
-
Key points: a colon
:at the end ofif/elif/else; 4-space indentation;elifandelseare optional; Python checks from top to bottom and stops at the first condition that is True — so order matters (marks ≥ 80 must be checked before ≥ 60). - Nested if = an
ifinside anif(double indentation = 8 spaces). - Truthiness:
if jina:is True ifjinais not an empty string.if 0:is False. - String comparison is case-sensitive: use
.lower()on user input:if jibu.lower() == "ndiyo":. - Ternary (briefly, no need to teach it in depth):
hali = "mtu mzima" if umri >= 18 else "mtoto".
Say this to the student
- "
ifis like a crossroads. When you get there, you look at the sign: 'if it is raining, take an umbrella; otherwise (else), wear a sun hat'." - "
elifis like a door guard going through a list in order: 'Do you have a VIP card? Enter door A. No? Do you have a regular ticket? Door B. No? You can't come in (else).' Once the guard gets the first answer, the others aren't checked." - "Indentation is like indented paragraphs in a notebook — the lines moved inward 'belong' to the
ifabove them."
Type this code live (share screen)
Step 1 — if and else (maamuzi.py, decisions)
umri = int(input("Umri wako: ")) if umri >= 18: print("Wewe ni mtu mzima.") print("Unaweza kupiga kura.") else: print("Bado wewe ni mtoto.") print(f"Subiri miaka {18 - umri} zaidi.") print("Asante!") # huu uko nje ya if — unafanyika kila mara
Run it twice (age 25, then 15):
Umri wako: 25 Wewe ni mtu mzima. Unaweza kupiga kura. Asante!
Umri wako: 15 Bado wewe ni mtoto. Subiri miaka 3 zaidi. Asante!
Step 2 — elif: grade bands for marks (the NECTA system, simplified)
alama = int(input("Alama (0-100): ")) if alama < 0 or alama > 100: print("Alama si sahihi!") elif alama >= 75: print("Daraja: A") elif alama >= 65: print("Daraja: B") elif alama >= 45: print("Daraja: C") elif alama >= 30: print("Daraja: D") else: print("Daraja: F")
Ask: "A mark of 80 is also >= 65. Why doesn't it show B?" → Because Python stops at the first condition that is True (>= 75).
Show the wrong order:
alama = 80 if alama >= 30: print("D") # inasimama hapa! si sahihi elif alama >= 75: print("A")
Step 3 — Nested if
ana_tiketi = input("Una tiketi? (ndiyo/hapana): ").strip().lower() if ana_tiketi == "ndiyo": umri = int(input("Umri: ")) if umri >= 18: print("Karibu kwenye tamasha!") else: print("Samahani, tamasha ni la watu wazima tu.") else: print("Nunua tiketi kwanza.")
Step 4 — Combining and/or instead of nesting
siku = input("Leo ni siku gani? ").strip().lower() if siku == "jumamosi" or siku == "jumapili": print("Ni wikendi! Pumzika.") else: print("Ni siku ya kazi/shule.")
Step 5 — Big example: simple ATM (atm.py)
salio = 150000 PIN_SAHIHI = "1234" pin = input("Weka PIN: ") if pin != PIN_SAHIHI: print("PIN si sahihi. Kadi imezuiliwa.") else: print("1. Angalia salio") print("2. Toa pesa") chaguo = input("Chagua (1/2): ") if chaguo == "1": print(f"Salio lako ni {salio:,} TZS") elif chaguo == "2": kiasi = int(input("Kiasi cha kutoa: ")) if kiasi <= 0: print("Kiasi si sahihi.") elif kiasi > salio: print("Salio halitoshi.") elif kiasi % 1000 != 0: print("ATM inatoa noti za 1,000 na kuendelea tu.") else: salio -= kiasi print(f"Chukua pesa zako. Salio jipya: {salio:,} TZS") else: print("Chaguo si sahihi.")
Example:
Weka PIN: 1234 1. Angalia salio 2. Toa pesa Chagua (1/2): 2 Kiasi cha kutoa: 50000 Chukua pesa zako. Salio jipya: 100,000 TZS
Questions to ask the student
- Why do we put
:at the end of anif? — Answer: It is a Python rule; it shows that a block is starting. - How many
elifs can anifhave? — Answer: Any number; only oneelse, and it comes last. - If
x = 0, what willif x:do? — Answer: It skips the block, because 0 is "falsy". - Why do we use
.lower()on the user's answer? — Answer: So that "Ndiyo", "NDIYO" and "ndiyo" (yes) are all accepted. - The difference between two
if...ifs andif...elif? — Answer: Twoifs are both checked;elifis checked only if the first was False.
Common mistakes
| Mistake | Error message | Fix |
|---|---|---|
Forgetting : |
SyntaxError: expected ':' |
if umri >= 18: |
| Not indenting | IndentationError: expected an indented block after 'if' statement on line 3 |
Add 4 spaces. |
| Inconsistent indentation | IndentationError: unindent does not match any outer indentation level |
Lines in one block must have the same number of spaces; don't mix Tabs and spaces. |
= instead of == |
if x = 5: → SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
== |
else with a condition |
else alama < 30: → SyntaxError: expected ':' |
else: has no condition; use elif. |
| Comparing a str and an int | input() == 5 is always False |
int(input()) or compare with "5". |
if x == "a" or "b": |
Always True (a bug, not an error!) | if x == "a" or x == "b": |
| Wrong order of elif | Incorrect grade | Check the largest first. |
In-class exercise
- Ask for a number; say whether it is positive, negative or zero, and whether it is even or odd.
- Ask for three numbers; display the largest (without using
max()). - Transport fare: ask for the distance (km) and whether the passenger is a student. Fare = 500 TZS per km for the first 10 km, 300 for each km after that. Students get a 50% discount.
Answer
# zoezi 1 n = int(input("Namba: ")) if n > 0: print("Chanya") elif n < 0: print("Hasi") else: print("Sifuri") if n % 2 == 0: print("Shufwa") else: print("Witiri")
# zoezi 2 a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) if a >= b and a >= c: kubwa = a elif b >= a and b >= c: kubwa = b else: kubwa = c print("Kubwa zaidi:", kubwa)
# zoezi 3 km = float(input("Umbali (km): ")) mwanafunzi = input("Mwanafunzi? (ndiyo/hapana): ").strip().lower() if km <= 10: bei = km * 500 else: bei = 10 * 500 + (km - 10) * 300 if mwanafunzi == "ndiyo": bei = bei * 0.5 print(f"Bei ya usafiri: {bei:,.0f} TZS") # km 15, si mwanafunzi -> 5000 + 1500 = 6,500 TZS
Session 3 — Loops: while, for, range, break, continue + the Bahatisha Namba Game
Session flow
- Homework review
whileloop, counter, infinite loop andCtrl+Cforloop over a string,range()- Break
breakandcontinue, thewhile Truepattern- Mini game: Bahatisha Namba (
random) — we build it step by step - Review of the week
- Q&A + homework
Explanation for the teacher (read this first)
- Loop = repeating a block of code many times.
while sharti:— repeats as long as the condition is True. It checks the condition before each iteration. Something inside the loop must change the situation, otherwise the loop never ends (an infinite loop) → stop it withCtrl + C(you will seeKeyboardInterrupt).for kitu in mfuatano:(kitu= item,mfuatano= sequence) — goes through each element of a sequence (string, range, list...). Used when we know the number of iterations.range():range(5)→ 0, 1, 2, 3, 4 (does not include 5)range(1, 6)→ 1, 2, 3, 4, 5range(0, 20, 5)→ 0, 5, 10, 15range(10, 0, -1)→ 10, 9, ..., 1
break— leave the loop immediately.continue— skip the rest of this iteration and go to the next one.- Important pattern:
while True:+break— for programs that repeat until the user says "acha" (stop). - Accumulator pattern:
jumla = 0before the loop,jumla += xinside. random:import randomat the top of the file;random.randint(1, 100)→ a random number from 1 to 100 (both ends are included, unlikerange).
Say this to the student
- "
whileis like eating rice: 'as long as you are still hungry, keep eating'. When you are full (the condition is False), you stop." - "
foris like a teacher calling names on a list — starts with the first, finishes with the last, each one once." - "
breakis like a fire alarm — everyone leaves the building immediately.continueis like saying 'skip this one, go on to the next'." - "An infinite loop is like a car with no brakes.
Ctrl + Cis the emergency brake."
Type this code live (share screen)
Step 1 — while (loops.py)
hesabu = 1 while hesabu <= 5: print("Mzunguko namba", hesabu) hesabu += 1 print("Loop imeisha")
Mzunguko namba 1 Mzunguko namba 2 Mzunguko namba 3 Mzunguko namba 4 Mzunguko namba 5 Loop imeisha
Then delete hesabu += 1 and run → infinite loop → Ctrl + C. "That's why something must change inside the loop."
Step 2 — Countdown
n = 5 while n > 0: print(n) n -= 1 print("Uzinduzi! 🚀")
Step 3 — for over a string
for herufi in "Python": print(herufi)
P y t h o n
neno = "mamba" idadi_a = 0 for h in neno: if h == "a": idadi_a += 1 print(f"Herufi 'a' ziko {idadi_a}") # Herufi 'a' ziko 2
Step 4 — range()
for i in range(5): print(i, end=" ") # 0 1 2 3 4 print() for i in range(1, 6): print(i, end=" ") # 1 2 3 4 5 print() for i in range(0, 21, 5): print(i, end=" ") # 0 5 10 15 20 print() for i in range(10, 0, -2): print(i, end=" ") # 10 8 6 4 2 print()
Step 5 — Multiplication table + total (accumulator)
n = int(input("Jedwali la namba gani? ")) for i in range(1, 11): print(f"{n} x {i:>2} = {n * i:>3}") jumla = 0 for i in range(1, 101): jumla += i print("Jumla ya 1 hadi 100 ni", jumla) # 5050
Jedwali la namba gani? 7 7 x 1 = 7 7 x 2 = 14 ... 7 x 10 = 70 Jumla ya 1 hadi 100 ni 5050
Step 6 — break and continue
for i in range(1, 11): if i == 7: break print(i, end=" ") print() # 1 2 3 4 5 6 for i in range(1, 11): if i % 3 == 0: continue print(i, end=" ") print() # 1 2 4 5 7 8 10
Step 7 — The while True pattern
jumla = 0 while True: maandishi = input("Weka namba (au 'q' kuacha): ") if maandishi == "q": break if not maandishi.isdigit(): print("Hiyo si namba, jaribu tena.") continue jumla += int(maandishi) print("Jumla:", jumla)
Step 8 — MINI GAME: Bahatisha Namba (bahatisha.py). Build it in 3 stages, running each stage.
Version 1 (one attempt):
import random siri = random.randint(1, 20) jaribio = int(input("Nimefikiria namba kati ya 1 na 20. Bahatisha: ")) if jaribio == siri: print("Umepata!") else: print(f"Hapana, ilikuwa {siri}")
Version 2 (repeat until they get it, with hints):
import random siri = random.randint(1, 20) while True: jaribio = int(input("Bahatisha (1-20): ")) if jaribio < siri: print("Juu zaidi ⬆") elif jaribio > siri: print("Chini zaidi ⬇") else: print("Umepata! 🎉") break
Version 3 (complete: limited attempts, counting, input checking, playing again):
import random print("=== MCHEZO WA BAHATISHA NAMBA ===") while True: # loop ya "cheza tena" siri = random.randint(1, 100) majaribio_max = 7 majaribio = 0 ameshinda = False print(f"\nNimefikiria namba kati ya 1 na 100. Una majaribio {majaribio_max}.") while majaribio < majaribio_max: jibu = input(f"Jaribio {majaribio + 1}: ").strip() if not jibu.isdigit(): print("Tafadhali andika namba tu.") continue # haihesabiwi kama jaribio jaribio = int(jibu) if jaribio < 1 or jaribio > 100: print("Namba iwe kati ya 1 na 100.") continue majaribio += 1 if jaribio < siri: print("Juu zaidi ⬆") elif jaribio > siri: print("Chini zaidi ⬇") else: print(f"Hongera! Umepata {siri} kwa majaribio {majaribio}.") ameshinda = True break if not ameshinda: print(f"Pole! Majaribio yamekwisha. Namba ilikuwa {siri}.") tena = input("Cheza tena? (ndiyo/hapana): ").strip().lower() if tena != "ndiyo": print("Kwaheri! 👋") break
Example:
=== MCHEZO WA BAHATISHA NAMBA === Nimefikiria namba kati ya 1 na 100. Una majaribio 7. Jaribio 1: 50 Chini zaidi ⬇ Jaribio 2: 25 Juu zaidi ⬆ Jaribio 3: 37 Hongera! Umepata 37 kwa majaribio 3. Cheza tena? (ndiyo/hapana): hapana Kwaheri! 👋
Extra question to get them thinking: "What is the best guessing strategy?" → Start in the middle (50), then the middle of the remaining half (binary search). This way 7 attempts are always enough for 1–100 (2^7 = 128).
Note: emoji display well in the VS Code terminal. If a particular terminal shows strange symbols, remove them — they are not important.
Questions to ask the student
- What numbers does
range(3)give? — Answer: 0, 1, 2. - Can
random.randint(1, 6)give 6? — Answer: Yes, it includes both ends. - When should we use
whileinstead offor? — Answer:whilewhen we don't know the number of iterations (e.g. until the user guesses correctly);forwhen we do (e.g. 10 times, or every character). - The difference between
breakandcontinue? — Answer:breakleaves the whole loop;continueskips only this iteration. - What does this code print?
for i in range(2, 10, 3): print(i)— Answer: 2, 5, 8. - How would you stop a stuck program? — Answer:
Ctrl + Cin the terminal.
Common mistakes
| Mistake | Error message | Fix |
|---|---|---|
| Infinite loop | The program never ends; pressing Ctrl+C → KeyboardInterrupt |
Make sure the condition variable changes inside the loop. |
Forgetting import random |
NameError: name 'random' is not defined. Did you forget to import 'random'? |
import random at the top of the file. |
Naming a file random.py |
AttributeError: module 'random' has no attribute 'randint' |
Don't name your file after a Python module. Rename it and delete the __pycache__ folder. |
Thinking range(1, 10) includes 10 |
It ends at 9 | range(1, 11) |
| Putting the accumulator inside the loop | jumla = 0 inside the loop → it goes back to 0 every time |
Put jumla = 0 before the loop. |
int() on non-numeric input |
ValueError: invalid literal for int() with base 10: 'abc' |
Check with .isdigit() first. |
break outside a loop |
SyntaxError: 'break' outside loop |
break must be inside a for/while. |
Forgetting : after for/while |
SyntaxError: expected ':' |
for i in range(5): |
In-class exercise
- Print all even numbers between 1 and 30 on one line.
- Ask for a word; count the vowels (a, e, i, o, u) in it.
-
Draw a triangle of stars with a height chosen by the user:
* ** ***
-
Add to the guessing game: the user chooses a level (1 = easy 1–10, 2 = medium 1–50, 3 = hard 1–100).
Answer
# zoezi 1 for i in range(2, 31, 2): print(i, end=" ") print()
# zoezi 2 neno = input("Neno: ").lower() vokali = 0 for h in neno: if h in "aeiou": vokali += 1 print("Vokali:", vokali)
# zoezi 3 urefu = int(input("Urefu: ")) for i in range(1, urefu + 1): print("*" * i)
# zoezi 4 (sehemu ya kuongeza mwanzoni mwa mchezo) import random kiwango = input("Kiwango (1=rahisi, 2=kati, 3=kigumu): ").strip() if kiwango == "1": juu = 10 elif kiwango == "2": juu = 50 else: juu = 100 siri = random.randint(1, juu) print(f"Bahatisha namba kati ya 1 na {juu}") while True: jaribio = int(input("Jaribio: ")) if jaribio < siri: print("Juu zaidi") elif jaribio > siri: print("Chini zaidi") else: print("Umepata!") break
Homework
HW1 (after Session 1, bring to Session 2): barua_pepe.py (email) — ask for the first and last name; create an email in the format jina.mwisho@shule.ac.tz (lowercase, no spaces at the edges). Also display the username (the part before @) using .find("@") and slicing.
HW2 (after Session 2, bring to Session 3): kodi.py (tax) — ask for the monthly salary. Tax: up to 270,000 → 0%; 270,001–520,000 → 8%; 520,001–760,000 → 20%; over 760,000 → 25% (for simplicity, a percentage of the whole salary). Display the tax and the net salary using an f-string with commas.
HW3 (after Session 3, bring to the next session): fizzbuzz.py — for the numbers 1 to 30: if divisible by 3 write "Fizz", by 5 "Buzz", by 3 and 5 "FizzBuzz", otherwise the number itself. Bonus: pin.py — the user has 3 attempts to enter the correct PIN ("2580"); after 3 → "Kadi imezuiliwa" (card blocked).
Answer
# barua_pepe.py kwanza = input("Jina la kwanza: ").strip().lower() mwisho = input("Jina la mwisho: ").strip().lower() email = f"{kwanza}.{mwisho}@shule.ac.tz" print("Email:", email) mahali = email.find("@") print("Jina la mtumiaji:", email[:mahali])
# kodi.py mshahara = float(input("Mshahara wa mwezi: ")) if mshahara <= 270000: kiwango = 0 elif mshahara <= 520000: kiwango = 0.08 elif mshahara <= 760000: kiwango = 0.20 else: kiwango = 0.25 kodi = mshahara * kiwango print(f"Kodi: {kodi:,.0f} TZS") print(f"Mshahara halisi: {mshahara - kodi:,.0f} TZS")
# fizzbuzz.py for n in range(1, 31): if n % 15 == 0: # lazima ikaguliwe kwanza! print("FizzBuzz") elif n % 3 == 0: print("Fizz") elif n % 5 == 0: print("Buzz") else: print(n)
# pin.py PIN = "2580" majaribio = 0 while majaribio < 3: pin = input("PIN: ") majaribio += 1 if pin == PIN: print("Karibu!") break else: print(f"Si sahihi. Majaribio yaliyobaki: {3 - majaribio}") else: print("Kadi imezuiliwa")
Remember: while ... else — the else runs if the loop ended without a break. It is an extra feature; if it is too hard, use a variable amefanikiwa = False (succeeded) instead.
If you are asked a question you don't know
- Try it together in the REPL — strings and
rangeare easy to test on the spot (list(range(2, 10, 3))shows all the numbers in a range). - Search: "python string methods", "python f-string format number", "python while vs for".
- Docs: https://docs.python.org/3/library/stdtypes.html#string-methods , https://docs.python.org/3/tutorial/controlflow.html , https://docs.python.org/3/library/random.html
End-of-week checklist
- Uses indexing (including negative) and knows the index starts at 0
- Does slicing
[a:b],[:b],[a:],[::-1] - Knows strings are immutable and writes
s = s.upper() - Uses methods:
strip,lower/upper/title,replace,split,find,count,isdigit - Writes f-strings with
:.2f,:, - Writes
if/elif/elsewith:and correct indentation - Understands why the order of
elifmatters - Writes nested
if - Uses
whileand knows how to stop an infinite loop withCtrl+C - Uses
forandrange()(start, stop, step) - Uses
break,continue, and thewhile Truepattern - Has written a working Bahatisha Namba game