šŖ How to practice properly
Nobody learned to ride a bike by watching videos about bikes. Programming is exactly the same: you only really learn it by typing code, breaking it, and fixing it. This page is your gym.
- Type every line yourself ā no copy-paste. Your fingers learn too.
- Guess the answer first, then press ā¶ Run and see if you were right.
- Get stuck for a while. Ten minutes of being stuck teaches more than the solution does.
- Only then press š” Solution ā and afterwards, close it and write the whole thing again from memory.
- Three challenges a day beats twenty challenges once a month. š
The challenges mix everything from the whole course: variables, loops, lists, dictionaries, functions, classes and algorithms. If one uses something you have not met yet, go and read that lesson ā then come back and beat it. š„
š„ Warm-Up Round
Five to ten minutes each. Perfect for a daily practice session ā do three every day and you will be amazed in a month.
Challenge 1: Numbered Shopping List
EasyPrint the list ["milk", "eggs", "bread"] as a numbered list: 1. milk and so on.
items = ["milk", "eggs", "bread"]
for i, item in enumerate(items, start=1):
print(f"{i}. {item}")
Challenge 2: Even Numbers Total
EasyAdd up every even number from 1 to 20 and print the total.
total = 0
for n in range(1, 21):
if n % 2 == 0:
total += n
print(total)
Challenge 3: Count the Vowels
EasyCount how many vowels (a, e, i, o, u) are in "programming is powerful" and print the number.
text = "programming is powerful"
count = 0
for letter in text:
if letter in "aeiou":
count += 1
print(count)
Challenge 4: Biggest of Three
EasyWithout using max(), print the biggest of a = 17, b = 42 and c = 23.
a, b, c = 17, 42, 23
biggest = a
if b > biggest:
biggest = b
if c > biggest:
biggest = c
print(biggest)
Challenge 5: Backwards List
EasyPrint [1, 2, 3, 4, 5] reversed ā first with slicing [::-1], then by looping backwards with range(len(items) - 1, -1, -1) printing one per line.
items = [1, 2, 3, 4, 5]
print(items[::-1])
for i in range(len(items) - 1, -1, -1):
print(items[i])
Challenge 6: Temperature Table
EasyPrint a small conversion table for 0, 10, 20 and 30 °C in the form 0C = 32.0F. Formula: c * 9 / 5 + 32.
for c in [0, 10, 20, 30]:
print(f"{c}C = {c * 9 / 5 + 32}F")
Challenge 7: Initials Maker
EasyTurn "grace brewster hopper" into G.B.H. ā split the name, take each first letter, uppercase it and add a dot.
name = "grace brewster hopper"
initials = ""
for part in name.split():
initials += part[0].upper() + "."
print(initials)
Challenge 8: Digit Sum
EasyAdd up the digits of 9174 (9 + 1 + 7 + 4) and print the answer. Use % and //, or turn it into text ā your choice.
n = 9174
total = 0
while n > 0:
total += n % 10
n = n // 10
print(total)
š§ Brain Builders
These take real thinking. Read the goal twice, plan on paper, then code. Getting stuck is part of the exercise ā stay with it before peeking at the solution.
Challenge 9: Password Generator
MediumUsing random.seed(7) so the answer is the same every run, build an 8-character password by picking random letters from "abcdefghijkmnpqrstuvwxyz23456789". Print it.
import random
random.seed(7)
alphabet = "abcdefghijkmnpqrstuvwxyz23456789"
password = ""
for i in range(8):
password += random.choice(alphabet)
print(password)
Challenge 10: Sentence Statistics
MediumFor "the quick brown fox jumps over the lazy dog", print the number of words, the longest word, and the average word length rounded to 2 decimals.
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
longest = words[0]
total_letters = 0
for word in words:
total_letters += len(word)
if len(word) > len(longest):
longest = word
print(len(words))
print(longest)
print(round(total_letters / len(words), 2))
Challenge 11: Second Largest
MediumFind the second largest number in [12, 45, 7, 98, 33, 98] ā careful, the biggest number appears twice, and the answer is 45, not 98!
numbers = [12, 45, 7, 98, 33, 98] unique = sorted(set(numbers)) print(unique[-2])
Challenge 12: Prime Checker
MediumWrite is_prime(n) (a number bigger than 1 with no divisors except 1 and itself), then print every prime from 1 to 30 on one line.
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
return False
return True
for n in range(1, 31):
if is_prime(n):
print(n, end=" ")
print()
Challenge 13: Caesar Cipher
MediumShift every letter of "attack at dawn" three places along the alphabet (aād, zāc), leaving spaces alone. Print the secret message.
message = "attack at dawn"
alphabet = "abcdefghijklmnopqrstuvwxyz"
secret = ""
for ch in message:
if ch == " ":
secret += " "
else:
secret += alphabet[(alphabet.index(ch) + 3) % 26]
print(secret)
Challenge 14: Class Report
MediumFrom grades = {"Ana": 88, "Ben": 61, "Cy": 94, "Di": 72}, print the average (2 decimals), the top student's name, and how many scored 70 or more.
grades = {"Ana": 88, "Ben": 61, "Cy": 94, "Di": 72}
print(round(sum(grades.values()) / len(grades), 2))
print(max(grades, key=grades.get))
passed = 0
for score in grades.values():
if score >= 70:
passed += 1
print(passed)
Challenge 15: Fibonacci List
MediumBuild a list of the first 12 Fibonacci numbers (each one is the sum of the two before, starting 0, 1) and print the list.
fib = [0, 1]
while len(fib) < 12:
fib.append(fib[-1] + fib[-2])
print(fib)
Challenge 16: Guess Checker
MediumWithout any input(), simulate a guessing game: secret = 42 and guesses = [10, 60, 40, 42, 7]. Print too low, too high or correct! for each guess, and stop as soon as it is correct.
secret = 42
guesses = [10, 60, 40, 42, 7]
for guess in guesses:
if guess < secret:
print("too low")
elif guess > secret:
print("too high")
else:
print("correct!")
break
š Boss Battles
The big ones. Each of these is a real classic that programmers meet in interviews and competitions. Take your time ā half an hour on one of these teaches more than an hour of easy tasks.
Challenge 17: Collatz Sequence
BossStart at 27. If the number is even, halve it; if it is odd, triple it and add one. Repeat until you reach 1, counting the steps. Print how many steps it took (it is famously more than you expect!).
n = 27
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
print(steps)
Challenge 18: Tic-Tac-Toe Judge
BossThe board is [["X", "O", "O"], ["O", "X", "O"], ["O", "O", "X"]]. Check all three rows, all three columns and both diagonals, then print the winner (X) or nobody.
board = [["X", "O", "O"], ["O", "X", "O"], ["O", "O", "X"]]
lines = []
for row in board:
lines.append(row)
for c in range(3):
lines.append([board[r][c] for r in range(3)])
lines.append([board[i][i] for i in range(3)])
lines.append([board[i][2 - i] for i in range(3)])
winner = "nobody"
for line in lines:
if line[0] == line[1] == line[2] != " ":
winner = line[0]
print(winner)
Challenge 19: Roman Numerals
BossTurn 1994 into MCMXCIV. Work through the values from biggest to smallest (1000=M, 900=CM, 500=D, 400=CD, 100=C, 90=XC, 50=L, 40=XL, 10=X, 9=IX, 5=V, 4=IV, 1=I), subtracting as you go.
number = 1994
values = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
roman = ""
for value, letters in values:
while number >= value:
roman += letters
number -= value
print(roman)
Challenge 20: Decimal to Binary
BossConvert 156 into binary without using bin(): keep dividing by 2 and collecting the remainders backwards. Print your answer, then print bin(156)[2:] to prove it matches.
n = 156
binary = ""
while n > 0:
binary = str(n % 2) + binary
n = n // 2
print(binary)
print(bin(156)[2:])
Challenge 21: Bank Account Class
BossWrite an Account class with deposit, withdraw (refusing overdrafts) and history() returning the list of every transaction. Deposit 100, withdraw 30, try to withdraw 500, then print the balance and the history.
class Account:
def __init__(self):
self.balance = 0
self.log = []
def deposit(self, amount):
self.balance += amount
self.log.append(f"+{amount}")
def withdraw(self, amount):
if amount > self.balance:
self.log.append(f"refused {amount}")
return False
self.balance -= amount
self.log.append(f"-{amount}")
return True
def history(self):
return self.log
account = Account()
account.deposit(100)
account.withdraw(30)
account.withdraw(500)
print(account.balance)
print(account.history())
Challenge 22: Word Ladder Counter
BossTwo words are "neighbors" if they differ in exactly one letter. From ["cold", "cord", "card", "ward", "warm"], print each neighboring pair like cold-cord, one per line.
words = ["cold", "cord", "card", "ward", "warm"]
def differ_by_one(a, b):
if len(a) != len(b):
return False
differences = 0
for i in range(len(a)):
if a[i] != b[i]:
differences += 1
return differences == 1
for i in range(len(words)):
for j in range(i + 1, len(words)):
if differ_by_one(words[i], words[j]):
print(f"{words[i]}-{words[j]}")
šØ Creative Lab
No right answers here ā just build something you think is cool and show someone. This is where practice turns into real programming.
Challenge 23: Free Play ā Your Own Quiz
CreativeBuild a 5-question quiz about anything you love. Keep the questions and answers in a list or dictionary, ask them with input(), count the score, and print a fun ending message. š
Challenge 24: Free Play ā ASCII Animation
CreativeUse loops and print() to make something move down the screen: a falling star, a growing tree, a rocket climbing. Print many frames one after another. š
Challenge 25: Free Play ā Invent a Challenge
CreativeInvent a practice task you think would be hard for a friend, then solve it yourself. Write the goal as a comment at the top, then the code below. Making good problems is how teachers learn too! š”