A complete KS4 Python course for schools. Students learn through PRIMM tasks with an in-browser IDE, AI marking, AI chat help, and Parsons problems — all runnable on your own school server.
The Code Ladder helps students move from reading code to writing their own programs. It is organised into 10 levels (Outputting through Sub-Programs). Each sub-level follows the PRIMM approach:
Progress is stored in the student’s browser only (cookies / localStorage). Nothing is uploaded to a central student database. Teachers can still collect evidence via the Progress Report (download, print/PDF, or email).
auth.js (default changeme — change this before sharing with students).
Parsons problems use separate passwords listed below.
Schools can host the full site themselves (lessons, IDE, Parsons, AI marking, and AI chat) using their own OpenAI API key.
1. Download the package
Download CodeLadder-SelfHost-20260815.zip
Also available at the site root as CodeLadder-SelfHost-20260815.zip.
2. What you need
curl and sessionsapi.openai.com3. Install
public/ and secrets/.public/ only (on shared hosting: put public/ contents into public_html, and put secrets/ one level above it).secrets/apikey.txt.example → secrets/apikey.txt and paste your real OpenAI key on a single line (must start with sk-, no comment lines)./setup-check.php until every check is green.auth.js.Full notes are in HOSTING.md inside the ZIP. Student progress still stays in the browser — your server only holds the site files and your API key.
Give students the password only when you want them to use the Parsons support. Click a task to reveal the worked solution code.
1.1
Make password: 1.1
def output():
print("Hello World")
print("This is my first program")
output()
def output():
print("Adam")
print("06/03/1990")
print("Welcome")
output()
1.2
Make password: 1.2
def output():
print(7+5)
print(7*2)
output()
def output():
print(10*2)
print(10/2)
print(10+2)
print(10-2)
output()
1.3
Make password: 1.3
def output():
print(7**2)
print(155**2)
output()
def output():
print(5**3)
print(25**7)
output()
giraffe
Make password: giraffe
def output():
print((25* 9/5) + 32)
print(25+273.15)
output()
def output():
print(((42-32) * 5/9) + 273.15)
print((42 -32)*5/9)
output()
vole
Make password: mouse
def output():
print(4+5)
print(11*7)
print("Done")
output()
def output():
print("dave")
print(11*7)
print("Done")
output()
tiger
Make password: tiger
def output():
print(12/4)
print(3**2)
output()
def output():
print(15 + 10)
print(6 * 6)
print(100 / 20)
output()
cup
Make password: cup
def output():
print("Pizza") #Outputs Pizza
print("5") #Outputs ?
output()
def output():
print("golf") #Outputs golf
print("5") #number of hours
print(5*4) #total hours for month
output()
speaker
Make password: speaker
def output():
print("My name is Reece")#name
print("Greenfield Academy")#school
print("Computer Science")#subject
output()
def output():
print("my favourite animal is a fish")#pet
print("fish food")#food
print("7")#hours
output()
tooth
Make password: tooth
def output():
print("Welcome to the game")#
print("High Score:")#
print(5800)#
print("Levels Completed:")#
print(12)#
output()
def output():
print("Player_Alpha")
print("Minecraft")
print(35)
print(35 * 60)
output()
2.1
Make password: 2.1
def output():
name = input("What is your name?")
print("Hello ")
print(name)
output()
def output():
colour = input("What is your favourite colour?")
print (colour)
print("Nice colour")
output()
2.2
Make password: 2.2
def output():
pets=0
print(pets)
output()
def output():
year = 10
print(year)
output()
2.3
Make password: 2.3
def output():
name = input("Enter your name: ")
age = input("Enter your age: ")
print(name)
print(age)
output()
def output():
movie = input("Enter your favourite movie: ")
year = input("What year was it released? ")
print(movie)
print(year)
print(year+year)
output()
wash
Make password: table
def output():
first = input("First name: ")
surname = input("Surname: ")
print(first + " " + surname)
output()
def output():
team = input("Favourite team: ")
score = input("Score: ")
print(team + " scored " + score + " goals!")
output()
sheet
Make password: chair
def output():
hometown = input("Enter your hometown: ")#
year =input("Enter year you moved there: ")#
print(hometown + " sounds like an amazing place and you have lived there since " + year)#
output()
def describe_hobby():
hobby = input("Enter your favourite hobby: ")
start_age = input("At what age did you start it? ")
print("That's great! You've been enjoying " + hobby + " since you were " + start_age + " years old.")
describe_hobby()
tom
Make password: tom
def artist():
artist_name = input("Enter your artist name: ")#
artwork_title = input("Enter your artwork's title: ")#
print(artwork_title)#
print(artist_name)#
artist()
def artists():
artist_name = input("Enter your artist name: ")#
artwork_title = input("Enter your artwork's title: ")#
artist_name2 = input("Enter your artist name: ")#
artwork_title2 = input("Enter your artwork's title: ")#
artist_name3 = input("Enter your artist name: ")#
artwork_title3 = input("Enter your artwork's title: ")#
print("|-> " + artwork_title + " by " + artist_name )#
print("|-> " + artwork_title2 + " by " + artist_name2)#
print("|-> " + artwork_title3 + " by " + artist_name3)#
artists()
prayer
Make password: prayer
def pet_name_creator():
colour = input("Enter a colour: ")
animal = input("Enter an animal: ")
print("Your pet name could be: " + colour + " " + animal + "!")
pet_name_creator()
def pet_name_creator():
colour = input("Enter a colour: ")
power = input("Enter a power: ")
weapon = input("Enter a weapon: ")
print("You are the : " + colour + " " + power + "with a " + weapon + "!")
pet_name_creator()
heart
Make password: drive
def record_items():
item1 = input("Enter first item: ")
item2 = input("Enter second item: ")
print("First item: " + item1)
print("Second item: " + item2)
record_items()
def record_items():
food1 = input("Enter favourite food: ")
food2 = input("Enter second favourite food: ")
print("You entered: " + food1 + " as your favourite and " + food2 + " as your second favourite food")
record_items()
light
Make password: light
Youâre a wizardâs apprentice gathering two magical runes for a spell. You accidentally drop both runes into the same pouch slot (same variable), so only the last rune remains.
def collect_runes():
first_rune = input("Pick up your first rune: ")
second_rune = input("Pick up your second rune: ")
print("Runes in pouch: " + first_rune + " & " + second_rune)
collect_runes()
Youâre navigating a spaceship through uncharted space. You enter two sector codes (which look like numbers), but instead of summing coordinates, the computer glues them together.
def navigate():
x = input("Enter X-sector code: ")
y = input("Enter Y-sector code: ")
print("Destination: " + x + y)
navigate()
3.1
Make password: 3.1
Add code to line 7 so that qty is cast to int before multiplying by price.
def calculate_total():
qty = input("Enter quantity: ")
price = 5
qty=int(qty)
print("Total cost: " + str(qty * price))
calculate_total()
def get_discounted_price():
price = float(input("Enter original price: "))
rate = float(input("Enter discount rate (%): "))
discounted = price * (1 - rate)
print("Discounted price: " + str(discounted))
get_discounted_price()
3.2
Make password: 3.2
Modify the code to cast âmeasurementâ to float before doubling.
def double_measurement():
measurement = input("Enter measurement: ")
result = float(m) * 2
print("Double measurement: " + str(result))
double_measurement()
def convert_to_pounds():
kg = float(input("Enter weight in kg: "))
lbs = kg * 2.2
print("Weight in pounds: " + str(lbs))
convert_to_pounds()
3.3
Make password: 3.3
Modify the code to cast age to str on line 7 rather than on line 7.
def show_age():
age = 30
print("Your age is: " + str(age))
show_age()
def movie_info():
title = str(input("Enter movie title: "))#
year = int(input("Enter release year: "))#
print("Movie: " + title + " (" + str(year) + ")")#
movie_info()
orbit
Make password: orbit
Modify the code so that the remaining balance is correctly calculated before correctly casting and outputting on the next line.
def cash_withdrawal():
balance = input("Enter your balance: ")
withdrawal = input("Enter withdrawal amount: ")
remaining = 0
print("Remaining: " + remaining)
cash_withdrawal()
def transfer_funds():
acc_a = int(input("Enter balance for account A: "))
acc_b = int(input("Enter balance for account B: "))
diff = acc_a - acc_b
print("Difference: " + str(diff))
transfer_funds()
prism
Make password: ember
Modify the code to cast total to float and diners to int before division.
def split_bill():
total = float(input("Enter total bill: "))
diners = int(input("Enter number of diners: "))
share = total / diners
print("Each pays: " + str(share))
split_bill()
def average_score():
s1 = float(input("Enter first score: "))
s2 = float(input("Enter second score: "))
avg = (s1 + s2) / 2
print("Average score: " + str(avg))
average_score()
sphere
Make password: spark
Modify the code to cast both base and exponent to int before exponentiation.
def growth():
base = int(input("Enter growth base: "))
exponent = int(input("Enter growth exponent: "))
result = base ** exponent
print("Result: " + str(result))
growth()
def ant_population():
initial_population= int(input("Enter the initial ant population: "))#
years = int(input("Enter number of years to project into the future: "))#
new_population = initial_population* (2 ** years)#
print("Estimated population: " + str(new_population))#
ant_population()
plug
Make password: glasses
Modify the code so that length and width are cast to int before multiplication.
def area_rectangle():
length = int(input("Enter rectangle length (m): "))
width = int(input("Enter rectangle width (m): "))
area = length * width
print("Area: " + str(area))
area_rectangle()
def area_circle():
r = int(input("Enter circle radius (m): "))
area = 3.14 * r * r
print("Circle area: " + str(area))
area_circle()
screen
Make password: print
Modify the code so that l, w, and h each take an input from the user. These are cast to int on line 8 as part of the calculation, before being outputted on line 9.
def compute_volume():
length = input("Enter length (m): ")
width = input("Enter width (m): ")
height = input("Enter height (m): ")
vol = int(length) * int(width) * int(height)
print("Volume: " + str(vol))
compute_volume()
def cylinder_volume():
radius = int(input("Enter cylinder radius (m): "))
height = int(input("Enter cylinder height (m): "))
volume = 3.14 * radius * radius * height
print("Cylinder volume: " + str(volume))
cylinder_volume()
lid
Make password: finger
Modify the code so that diameter and slices are cast appropriately (int for slices, float for diameter), and compute area per slice using 3.14 * (diameter/2) * (diameter/2) / slices.
def pizza_slice_area():
diameter = float(input("Enter pizza diameter (in): "))
slices = int(input("Enter number of slices: "))
radius = diameter / 2
area = 3.14 * radius * radius
slice_area = area / slices
print("Slice area: " + str(slice_area))
pizza_slice_area()
def pizza_value():
diameter = float(input("Enter pizza diameter (in): "))
price = float(input("Enter pizza price (£): "))
slices = int(input("Enter number of slices: "))
radius = diameter / 2
area = 3.14 * radius * radius
cost_per_sq_in = price / area
cost_per_slice = price / slices
print("Cost per sq in: " + str(cost_per_sq_in))
print("Cost per slice: " + str(cost_per_slice))
pizza_value()
4.1
Make password: 4.1
Adapt the code below to check whether the weather is ârainyâ, if it is output an appropriate message.
def check_weather():
weather = input("What is the weather like? ")#
if weather == "sunny":#
print("Take some sun cream")#
elif weather == "rainy":#
print("Take a brolly")#
check_weather()#
Can be done as an if or elif.
def check_grade():
grade = int(input("Enter your test score: "))
if grade >= 70:
print("You passed!")
else:
print("Failed")
check_grade()
4.2
Make password: 4.2
Adapt this code to also output good afternoon if it is after 12pm using an elif.
def greet_time():
hour = int(input("Enter the hour (0-23): "))
if hour < 12:
print("Good morning")
elif hour >=12:
print("Good Afternoon")
greet_time()
def age_check():
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult")
age_check()
4.3
Make password: 4.3
Adapt the code below so that it also checks for temperatures below zero and over 30. Both with an appropriate message output.
def temperature_response():
temp = int(input("Enter temperature: "))
if temp < 0:
print("It's freezing")
elif temp < 10:
print("It's cold")
elif temp < 20:
print("It's warm")
elif temp > 30:
print("It's very warm")
temperature_response()
def food_rating():
rating = int(input("Rate the food (1-5): "))
if rating == 5:
print("Excellent!")
elif rating >= 3:
print("Good")
else:
print("Needs improvement")
food_rating()
slide
Make password: saw
Adapt the code to also identify toddlers (less than 3). You should also add a section to identify the adults (over 19).
def age_category():
age = int(input("Enter your age: "))#
if age < 3:#
print("Toddler")#
elif age < 13:#
print("Child")#
elif age < 20:#
print("Teen")#
else:#
print("Adult")#
age_category()
def check_login():
username = input("Enter username: ")
if username == "admin":
print("Access granted")
else:
print("Access denied")
check_login()
star
Make password: moon
Finish off this code for all of the houses of Hogwarts.
def check_colour():
colour1 = input("Enter your favourite colour: ")
colour2 = input("Enter your second favourite colour: ")
if colour1 == "red" or colour2 == "red":
print("That's Gryffindor!")
elif colour1 == "yellow" or colour2 == "yellow":
print("That's hufflepuff!")
elif colour1 == "blue" or colour2 == "blue":
print("That's ravenclaw!")
elif colour1 == "green" or colour2 == "green":
print("That's slytherin!")
check_colour()
def check_pins():
pin1 = input("Enter your pin: ")
pin2 = input("Re-enter your pin: ")
pin3 = input("Re-enter your pin again: ")
if pin1 == pin2 and pin2 == pin3:
print("Accepted")
else:
print("PIN Not Accepted")
check_pins()
sun
Make password: galaxy
Adapt the code so that it accepts the name âAdminâ or âSuperAdminâ
def login_warning():
name = input("Enter your username: ")
if name != "Admin" or name != "SuperAdmin":
print("Warning: Limited permissions")
login_warning()
def pin_check():
pin1 = input("Enter your 4-digit PIN: ")
pin2 = input("Re-enter your PIN: ")
if pin1 != pin2:
print("PINs do not match. Please try again.")
else:
print("PIN confirmed.")
pin_check()
road
Make password: link
Adapt the code so that it also checks for Isosceles (two sides are equal) and for Scalene (all sides are different).
def check_triangle():
side1 = int(input("Enter length of side 1: "))
side2 = int(input("Enter length of side 2: "))
side3 = int(input("Enter length of side 3: "))
if side1 == side2 and side2 == side3:
print("Equilateral triangle")
elif side1 == side2 or side2 == side3 or side3 == side1:
print("Isosceles triangle")
else:
print("Scalene triangle")
check_triangle()
def check_clearance():
codename = input("Enter your codename: ")
level = int(input("Enter your clearance level: "))
region = input("Enter your assigned region: ")
if codename != "Shadow" and level >= 5 and region == "North":
print("Access granted")
else:
print("Access denied")
check_clearance()
solar
Make password: lab
Modify the code so that it also checks that a user has a ticket.
def game_entry():
age = int(input("Enter your age: "))
ticket = input("Do you have a ticket? (yes/no): ")
if age >= 12 and ticket == "yes":
print("You may enter the game.")
else:
print("Sorry, you cannot enter the game.")
game_entry()
def shopping_discount():
is_member = input("Are you a member? (yes/no): ")
total_spent = float(input("Enter total spent: "))
if is_member == "yes" or total_spent > 100:
total = total_spent*0.9
print("You qualify for a discount! New Price: "+str(total))
else:
print("No discount. Price: "+ str(total_spent))
shopping_discount()
shore
Make password: shore
Adapt the code so that an appropriate message is displayed after each condition.
def login_system():
username = input("Enter username: ")
if username == "admin":
password = input("Enter Password")
if password == "letmein":
print("Access Granted")
else:
print("Access Denied")
else:
print("Access Denied")
login_system()
def age_category_check():
age = int(input("Enter your age: "))
if age >= 13:
student = input("Are you a student? (yes/no): ")
if student == "yes":
print("You can have a discounted ticket.")
age_category_check()
5.1
Make password: 5.1
def totals():
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Sum: " + str(a + b))
print("Difference: " + str(a - b))
totals()
def temperature_change():
start = int(input("Start temperature (°C): "))
highest = int(input("Highest temperature (°C): "))
final = highest - start
print("Temperature increase: " + str(final) + "°C")
temperature_change()
5.2
Make password: 5.2
def rectangle_triangle():
length = int(input("Length: "))
height = int(input("Width: "))
area = length * height
print("Rectangle Area: " + str(area))
triangle_area = area / 2
print("Triangle Area: " + str(triangle_area))
rectangle_triangle()
def average_of_three():
n1 = float(input("First score: "))
n2 = float(input("Second score: "))
n3 = float(input("Third score: "))
avg = (n1 + n2 + n3) / 3
print("Average: " + str(avg))
average_of_three()
5.3
Make password: 5.3
def precedence():
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
no_brackets = a + b * c
print("a + b * c = " + str(no_brackets))
with_brackets = (a + b) * c
print("(a + b) * c = " + str(with_brackets))
precedence()
def trip_cost():
students = int(input("Number of students: "))
entry_fee = float(input("Entry fee per student: "))
lunch_fee = float(input("Lunch fee per student: "))
coach_cost = float(input("Coach cost (fixed): "))
total_without_lunch = (students * entry_fee) + coach_cost
total_with_lunch = (students * (entry_fee + lunch_fee)) + coach_cost
print("Total cost without lunch = " + str(total_without_lunch))
print("Total cost with lunch = " + str(total_with_lunch))
trip_cost()
seat
Make password: frame
def odd_or_even():
num = int(input("Enter a whole number: "))
remainder = num % 2
print("Remainder when divided by 2 is: " + str(remainder))
if remainder == 0:
print("Even")
else:
print("Odd")
odd_or_even()
def box_packing():
total_books = int(input("Total books: "))
box_size = int(input("Books per box: "))
full_boxes = total_books // box_size
leftover_books = total_books % box_size
print("Full boxes: " + str(full_boxes))
print("Leftover books: " + str(leftover_books))
box_packing()
shirt
Make password: jersey
def yearbook_pages():
total = int(input("Total photos: "))
per_page = 9
full_pages = total // per_page
last_page_photos = total % per_page
total_pages = (total + per_page - 1) // per_page
print("Full pages: " + str(full_pages))
print("Photos on the last page: " + str(last_page_photos))
print("Total pages for the yearbook: " + str(total_pages))
yearbook_pages()
def assembly_seating():
total_students = int(input("Total students: "))
seats_per_row = int(input("Seats per row: "))
full_rows = total_students // seats_per_row
last_row_students = total_students % seats_per_row
empty_seats = (seats_per_row - last_row_students) % seats_per_row
print("Full rows: " + str(full_rows))
print("Students in the last row: " + str(last_row_students))
print("Empty seats in the last row: " + str(empty_seats))
assembly_seating()
extra
Make password: flower
def hours_mins():
minutes = int(input("Enter total minutes: "))
hours = minutes // 60
remaining_minutes = minutes % 60
print("H:M -> " + str(hours) + ":" + str(remaining_minutes))
hours_mins()
def seconds_to_hms():
secs = int(input("Enter total seconds: "))
hours = secs // 3600
rem = secs % 3600
minutes = rem // 60
seconds = rem % 60
print("H:M:S -> " + str(hours) + ":" + str(minutes) + ":" + str(seconds))
seconds_to_hms()
candle
Make password: desk
def powers():
n = int(input("Enter a number: "))
print("Square: " + str(n ** 2))
print("Cube: " + str(n ** 3))
powers()
def savings_growth():
start = float(input("Starting balance: "))
rate = float(input("Per-year interest rate (e.g., 1.1 for +10%): "))
years = int(input("Number of years: "))
final_value = start * (rate ** years)
print("Final value: " + str(final_value))
# Optional formatting:
print("Final value: £" + format(final_value, ".2f"))
savings_growth()
drawer
Make password: glass
def usb_fit():
capacity = int(input("USB capacity (MB): "))
file_size = int(input("File size (MB): "))
if file_size <= 0:
print("Invalid file size")
else:
fit = capacity // file_size
leftover = capacity % file_size
print("Files that fit: " + str(fit))
print("Leftover space (MB): " + str(leftover))
usb_fit()
def photo_folders():
total_photos = int(input("Total photos: "))
per_folder = int(input("Photos per folder: "))
if per_folder <= 0:
print("Invalid photos per folder")
else:
full_folders = total_photos // per_folder
last_folder_photos = total_photos % per_folder
print("There are: " + str(full_folders) +" full boxes, with "+ str(last_folder_photos)+ " in the final box")
photo_folders()
carpet
Make password: vase
def xp_level():
xp = int(input("Total XP: "))
level = xp // 1000
into_level = xp % 1000
print("Level: " + str(level))
print("XP into current level: " + str(into_level))
xp_level()
def battle_pass():
points = int(input("total points: "))
level_size = 150
levels_done = points // level_size
points_into = points % level_size
to_next = (level_size - points_into) % level_size
print("levels completed: " + str(levels_done))
print("points to next level: " + str(to_next))
battle_pass()
6.1
Make password: 6.1
def repeat():
for x in range (10):
print("Hello")
repeat()
def repeat():
for x in range (13):
print("Adam")
repeat()
NOTE - this will work for any name with an age of 14,15 or 16.
6.2
Make password: 6.2
def values():
for x in range (1,6):
print(x)
values()
def total_calculator():
total=0
for x in range (0,5):
number=int(input("Enter a number. "))
total=total+number
print(total)
total_calculator()
6.3
Make password: 6.3
def variables_as_counters():
number=int(input("Enter the number to repeat"))
for x in range (0,number):
print("Hello World")
variables_as_counters()
def times_table():
multiply_number = int(input("Enter a number to multiply by 2: "))
repeat_times = int(input("How many times should I repeat this? "))
for x in range(repeat_times):
total = multiply_number * 2
print (str(multiply_number) + " x 2 = " + str(total))
times_table()
cactus
Make password: song
def count_up_in_twos():
for i in range(0, 21, 2):
print(i)
count_up_in_twos()
def green_bottles():
start = int(input("Start number of bottles: "))
for n in range(start, 0, -1):
print(str(n) + " green bottles hanging on the wall")
print("And if one green bottle should accidentally fall,")
print("There'll be " + str(n - 1) + " green bottles hanging on the wall.")
print("")
print("There are no green bottles hanging on the wall.")
green_bottles()
audio
Make password: video
def count_one_to_five():
i = 1
while i < 5:
print(i)
i=i+1
count_one_to_five()
def countdown_from():
n = int(input("Start at: "))
while n >= 1:
print(n)
n = n - 1
print("Lift off!")
countdown_from()
steps
Make password: five
def read_valid_mark():
mark = int(input("Mark (0-100): "))
while mark > 100 or mark <0:
print("Invalid. Try again.")
mark = int(input("Mark (0-100): "))
print("Accepted: " + str(mark))
read_valid_mark()
def pin_checker():
pin = input("Enter 4-digit PIN: ")
while pin != "8945":
print("Incorrect.")
pin = input("Enter 4-digit PIN: ")
print("Access granted")
pin_checker()
steel
Make password: city
def running_total():
total = 0
entry = 0
while entry != "q":
total=total+int(entry)
entry = input("Enter number: ")
print("Total: "+ str(total))
running_total()
def total_and_average():
total = 0
count = 0
entry = input("Enter a number or q to quit: ")
while entry != "q":
total = total + int(entry)
count = count + 1
entry = input("Enter a number or q to quit: ")
if count == 0:
print("No data")
else:
print("Total:"+ str(total))
print("Average:"+ str(total / count))
total_and_average()
backstreet
Make password: boys
def add(number_1, number_2):
total = number_1 + number_2
print("Result: " + str(total))
menu()
def subtract(number_1, number_2):
total = number_1 - number_2
print("Result: " + str(total))
menu()
def multiply(number_1, number_2):
total = number_1 * number_2
print("Result: " + str(total))
menu()
def divide(number_1, number_2):
total = number_1 / number_2
print("Result: " + str(total))
menu()
def quit_msg():
print("Goodbye!")
def menu():
print("=== Calculator Menu ===")
print("[A] Add")
print("[S] Subtract")
print("[M] Multiply")
print("[D] Divide")
print("[q] Quit")
choice=input("Choose: ")
while choice != "q":
number_1 = float(input("First number: "))
number_2 = float(input("Second number: "))
if choice == "A" or choice =="a":
add(number_1, number_2)
elif choice == "S" or choice =="s":
subtract(number_1, number_2)
elif choice == "M" or choice =="m":
multiply(number_1, number_2)
elif choice == "D" or choice =="d":
divide(number_1, number_2)
else:
print("Invalid operation choice")
quit_msg()
menu()
def to_celsius(value):
total = (value-32)*5/9
print("Celsius:" + str(total))
def to_fahrenheit(value):
total =value*9/5+32
print("Fahrenheit: " + str(total))
choice = input("[C] FahrenheitâCelsius [F] CelsiusâFahrenheit [q] Quit: ")
while choice != "q":
if choice == "C" or choice == "c":
value = float(input("Enter F: "))
to_celsius(value)
elif choice == "F" or choice == "f":
value = float(input("Enter C: "))
to_fahrenheit(value)
else:
print("Invalid choice")
choice = input("[C] FahrenheitâCelsius [F] CelsiusâFahrenheit [q] Quit: ")
print("Goodbye!")
to_celsius()
foo
Make password: fighters
def hash_block(rows, cols):
for r in range(rows):
line = ""
for c in range(cols):
line = line + "^"
print(line)
print("100")
rows = 5
cols = 20
hash_block(rows, cols)
This can also be done by doing a count after the second loop. It could also be done by multiplying rows and columns. This is marked on output.
def times_table_grid(rows, cols):
for r in range(1, rows + 1):
line = ""
for c in range(1, cols + 1):
cell = r * c
if c == 1:
line = str(cell)
else:
line = line + " \t" + str(cell)
print(line)
rows = int(input("Rows (1-12): "))
cols = int(input("Cols (1-12): "))
times_table_grid(rows, cols)
7.1
Make password: 7.1
def extract_substring():
text = "Hello World" # comment
print(text[0:3]) # comment
print(text[6:9]) # comment
extract_substring()
def extract_substring():
name = input("Enter name") # comment
print(name[0:3]) # comment
extract_substring()
7.2
Make password: 7.2
def extract_from_index():
text = input("Enter name") # comment
print(text[:1]) # comment
print(text[1:]) # comment
extract_from_index()
def get_from_third():
word = input("Enter a word: ") # comment
from_third = word[2:] # comment
print(from_third) # comment
get_from_third()
7.3
Make password: 7.3
def extract_range():
text = "Computer" # comment
print(text[3:6]) # comment
extract_range()
def get_range():
word = input("Enter a word: ") # comment
range_chars = word[2:5] # comment
print(range_chars) # comment
get_range()
venga
Make password: venga
def access_characters():
text = "Python" # comment
print(text[0]) # comment
print(text[3]) # comment
access_characters()
def access_characters():
text = input("Enter a word") # comment
print(text[0]) # comment
print(text[3]) # comment
access_characters()
is
Make password: is
def iterate_word():
word = "Hello" # comment
for x in range(5): # comment
print(word[x]) # comment
iterate_word()
def iterate_word():
word = input("Enter a word") # comment
for x in range(0,len(word)): # comment
print(word[x]) # comment
iterate_word()
flames
Make password: flames
def reverse_word():
word = input("Enter word: ") # comment
print(word[::-1]) # comment
reverse_word()
def reverse_word():
word = input("Enter a word: ") # comment
reversed_word = word[::-1] # comment
print(word) # comment
print(reversed_word) # comment
if word == reversed_word: # comment
print("This is a palindrome") # comment
reverse_word()
habs
Make password: canucks
def count_vowels(word, count):
print(word) # comment
for x in range(0,len(word)): # comment
if word[x] == "a" or word[x] == "e" or word[x] == "i" or word[x] == "o" or word[x] == "u": # comment
count=count+1 # comment
return count # comment
word=input("Enter a word")
count=0
print(count_vowels(word,count))
def separate_letters(word):
vowels_list = "" # comment
consonants_list = "" # comment
for x in range(0, len(word)): # comment
if word[x] == "a" or word[x] == "e" or word[x] == "i" or word[x] == "o" or word[x] == "u": # comment
vowels_list = vowels_list + word[x] # comment
else: # comment
consonants_list = consonants_list + word[x] # comment
return (vowels_list,consonants_list) # comment
word = input("Enter a word: ")
print(separate_letters(word))
bruins
Make password: stars
def check_answer(answer): # define the function
if answer.lower() == "python": # check in lowercase
print("Correct") # correct message
else: # otherwise
print("Incorrect") # incorrect message
check_answer("PyThOn") # call with PyThOn
def quiz(): # define the quiz function
answer = input("What Colour is the sky?: A-Red, B-Green, or C-Blue? ") # get user input
if answer.upper() == "C": # check the correct option
print("Congratulations!") # correct message
else: # otherwise
print("Incorrect") # incorrect message
quiz() # call the function
caps
Make password: panthers
def show_digits(word): # function with word parameter
for ch in word: # loop through each character
if ch.isdigit(): # check if digit
print(ch) # print the digit
show_digits("H3ll0") # call with H3ll0
def letters_only(word): # function with word parameter
result = "" # build letters-only result
for ch in word: # loop through each character
if ch.isdigit(): # skip digits
pass # do nothing
else: # keep letters
result = result + ch # add to result
print(result) # output letters only
word = input("Enter a word: ") # get input
letters_only(word) # call the function
8.1
Make password: 8.1
def list():
numbers = [4, 7, 2, 9]
total=0
for n in numbers:
total=total+n
print(total)
list()
def show_names():
names = ["Ava", "Noah", "Luca", "Mia", "Ivy"]
for name in names:
print(name)
show_names()
8.2
Make password: 8.2
def show_colours():
colours = ["red", "blue", "green", "yellow"]
print(colours[0])
print(colours[-1])
show_colours()
def show_temps():
temps = [12, 15, 9, 18, 14, 11]
print("Highest:", max(temps))
print("Lowest:", min(temps))
show_temps()
8.3
Make password: 8.3
def add_score():
scores = [10, 20, 30]
new_score = 25
scores.append(new_score)
print(scores)
add_score()
def store_hobbies():
hobbies = []
for i in range(3):
hobby = input("Enter a hobby: ")
hobbies.append(hobby)
print(hobbies)
store_hobbies()
counter
Make password: even
def count_a():
letters = ["a", "b", "a", "c", "a"]
count = 0
for letter in letters:
if letter == "a":
count+=1
print(count)
count_a()
nums = [3, 8, 10, 7, 4, 1, 12, 5]
even_count = 0
for n in nums:
if n % 2 == 0:
even_count += 1
print("Even numbers:", even_count)
order
Make password: ranking
def sort_prices():
prices = [12, 4, 19, 7, 10]
prices.sort(reverse=True)
print(prices)
sort_prices()
def remove_largest():
numbers = []
for i in range(6):
num = int(input("Enter a number: "))
numbers.append(num)
largest = max(numbers)
numbers.remove(largest)
print(numbers)
remove_largest()
matrix
Make password: average
seats = [["A1", "A2"], ["B1", "B2"]]
for row in seats:
for seat in row:
print(seat)
scores = [[60, 70], [80, 75], [90, 85]]
for row in scores:
print(row)
avg = (row[0] + row[1]) / 2
print("Average:", avg)
index
Make password: iterate
grid = [[1, 2, 3], [4, 5, 6]]
for row in grid:
total = 0
for num in row:
total += num
print("Row total:", total)
stock = [["Pens", 12], ["Books", 3], ["Rulers", 8]]
for row in stock:
item = row[0]
qty = row[1]
print(item, qty)
if qty < 5:
print("Low stock")
subject
Make password: budget
table = [["Ann", "Math"], ["Ben", "Science"], ["Cara", "Math"]]
subject = "Math"
for row in table:
if row[1] == subject:
print(row[0])
games = [["FIFA", 50], ["Halo", 45], ["Stardew", 20]]
budget = int(input("Enter budget: "))
for row in games:
if row[1] <= budget:
print(row[0], row[1])
record
Make password: lookup
products = [["Pen", 2, 5], ["Book", 4, 3]]
for row in products:
value = row[1] * row[2]
print(row[0], value)
products = [["Pen", 2, 5], ["Book", 4, 3], ["Ruler", 1, 10]]
search = input("Enter product: ")
found = False
for row in products:
if row[0].lower() == search.lower():
value = row[1] * row[2]
print(row[0], value)
found = True
if found == False:
print("Not found")
9.1
Make password: 9.1
def read_file():
file = open("notes.txt", "r")
print(file.read()) # read the whole file
file.close()
read_file()
def flight():
file = open("manifest.txt", "r")
flight=(file.read(7))
if flight[4:7] == "MAN":
print("Have a great time in Manchester")
else:
print("Have a great trip")
file.close()
flight()
9.2
Make password: 9.2
def read_lines():
file = open("notes.txt", "r")
lines = file.readlines()
#print(lines) # notice the \n characters
#comment out the code on line 8 and un-comment line 11 and 12
for line in lines: # notice the difference?
if line[0:3] == "But":
print(line)
read_lines()
def find_user():
username = input("Enter your Username: ").strip().lower()
found = False
file = open("Users.txt", "r")
users = file.readlines()
file.close()
for line in users:
if line.strip().lower() == username:
print("User Found")
found = True
if not found:
print("User not found")
find_user()
9.3
Make password: 9.3
def add_note():
note = "Remember to bring your calculator."
file = open("8.4notes.txt", "w")
file.write("First note\n")
file.close()
# (Starter code currently overwrites the file. Change to append)
file = open("8.4notes.txt", "a")
file.write(note)
file.close()
file = open("8.4notes.txt", "r")
print(file.read())
file.close()
add_note()
def add_entry():
entry = input("Enter your Diary Entry for today")
date = input("What is todays date?")
# Append the diary entry
file = open("diary.csv", "a")
file.write(date + "," + entry + "\n")
file.close()
# Print the diary
file = open("diary.csv", "r")
print(file.read())
file.close()
add_entry()
folder
Make password: drawer
def count_lines():
file = open("poem.txt", "w")
file.write("Roses are red\nViolets are blue\nPython is fun\nAnd so are you\n")
file = open("poem.txt", "r")
lines = file.readlines()
print("Number of lines:", len(lines))
count_lines()
def count_word():
# Open the file for reading
file = open("story.txt", "r")
text = file.read()
words = text.split()
count = 0
for x in words:
if x == "the":
count += 1
print("'the' appears", count, "times in the story")
count_word()
line
Make password: count
def find_word():
file = open("poem.txt", "w")
file.write("Roses are red\nViolets are blue\nPython is fun\nAnd so are you\n")
file = open("poem.txt", "r")
text = file.read()
word = input("Enter a word to search for: ")
words = text.split()
count = 0
for w in words:
if w.lower() == word.lower():
count += 1
print(word, "appears", count, "times")
find_word()
def find_word():
file = open("story.txt", "r")
text = file.read()
file.close()
word = input("Enter a word to search for: ")
words = text.split()
count = 0
for w in words:
if w.lower() == word.lower():
count += 1
print("The word appears", count, "times")
find_word()
trim
Make password: total
def show_names():
file = open("names.txt", "r")
names = file.readlines()
file.close()
for name in names:
print(name.strip())
show_names()
def total_scores():
file = open("scores.txt", "r")
scores = file.readlines()
file.close()
total = 0
for score in scores:
total = total + int(score.strip())
print("Total score:", total)
total_scores()
search
Make password: flight
def show_flights():
file = open("flights.csv", "r")
for line in file:
data = line.split(",")
if data[1] == "Paris":
print(line)
file.close()
show_flights()
def find_flights():
dest = input("Enter destination: ")
file = open("flights.csv", "r")
found = False
for line in file:
data = line.split(",")
if data[1] == dest:
print(line)
found = True
if found == False:
print("No Flights Found")
file.close()
find_flights()
value
Make password: calculate
def show_stock():
file = open("stock.csv", "r")
for line in file:
data = line.split(",")
value = int(data[1]) * int(data[2])
print(data[0], value)
file.close()
show_stock()
def stock_value():
file = open("stock.csv", "r")
out = open("value.txt", "w")
for line in file:
data = line.split(",")
value = int(data[1]) * int(data[2])
out.write(data[0] + "," + str(value) + "\n")
file.close()
out.close()
stock_value()
parameter
Make password: console
def show_games(console):
file = open("games.csv", "r")
for line in file:
data = line.split(",")
if data[1] == console:
print(data[0])
file.close()
console = input("Enter console: ")
show_games(console)
def find_games(console):
file = open("games.csv", "r")
for line in file:
data = line.split(",")
if data[1] == console:
value = int(data[2]) * int(data[4])
print(data[0], value)
file.close()
console = input("Enter console: ")
find_games(console)
10.1
Make password: 10.1
def welcome():
print("Welcome to the game!")
welcome()
welcome()
welcome()
def show_score():
print("Your score is 100")
show_score()
show_score()
10.2
Make password: 10.2
def greet(name):
print("Hello " + name)
greet("Ava")
greet("Noah")
def greet(name):
print("Hello " + name)
name = input("Enter your name: ")
greet(name)
10.3
Make password: 10.3
def double(number):
print(number * 2)
double(15)
double(25)
def square(side):
print(side * side)
square(6)
paper
Make password: heat
def add(a, b, c):
print(a + b + c)
add(3, 4, 5)
def full_name(first, last):
print(first + " " + last)
first = input("Enter First Name: ")
last = input("Enter Last Name: ")
full_name(first, last)
keys
Make password: radio
def times_table(number):
for i in range(1, 13):
print(number * i)
times_table(2)
times_table(5)
times_table(10)
def draw_line(symbol, length):
print(symbol * length)
draw_line("#", 5)
draw_line("*", 3)
draw_line("=", 8)
Code Ladder · Teacher & self-host guide