Skip to content
Book 8: Algorithms, Programming and Databases

Book 8 · Chapter 8

Programming fundamentals

§8.1§8.2Exam craftB8·8

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

§8.1 Programming concepts

Short code B8·8·1

§8.2 Programming operators

Short code B8·8·2

Variables and constants

Short code B8·8·10

# A constant: its name is in capital letters
VAT_RATE = 0.2
# Variables, each initialised before it is used
each = 40
quantity = 3
cost = each * quantity
tax = cost * VAT_RATE
print("Cost:", cost)
print("Tax:", tax)
quantity = quantity + 2
print("Quantity now:", quantity)
Variables and a constant. Notice that VAT_RATE is written in capitals and never changes, while quantity is given a new value near the end.

Output

Cost: 120
Tax: 24.0
Quantity now: 5
Run and checked before printing

Data types

Short code B8·8·11

pupils = 28          # int
height = 1.5         # float
team = "Falcons"     # str
paid = True          # bool
print(team, "has", pupils, "pupils")
print(pupils + 2)
print(height * 100)
print(pupils / 4)
print(paid)
The four data types. Notice that / gave a float even though both numbers were whole, and that True prints without quotation marks.

Output

Falcons has 28 pupils
30
150.0
7.0
True
Run and checked before printing

Input and output

Short code B8·8·12

name = input()
age = int(input())
print("Hello", name)
print("Hello " + name + "!")
print("Next year you will be", age + 1)
print(name, "is", age, "years old")
Input and output. Inputs: Bilal, then 14. Notice that a comma in print() adds a space, but + joins strings with no space.

Output

Hello Bilal
Hello Bilal!
Next year you will be 15
Bilal is 14 years old
Run and checked before printing

Casting: changing the type

Short code B8·8·13

first = input()
second = input()
print(first + second)
print(int(first) + int(second))
Adding two numbers that are input. Inputs: 5, then 3.

Output

53
8
Run and checked before printing
text = "12"
number = int(text)
print(text + text)
print(number + number)
print(float(number))
print(int(7.9))
print(str(3) + str(4))
mark = 85
print("Mark: " + str(mark))
Casting. Notice the first two lines: the same characters give 1212 as strings but 24 as integers.

Output

1212
24
12.0
7
34
Mark: 85
Run and checked before printing

Sequence and selection: if, elif and else

Short code B8·8·14

mark = int(input())
if mark >= 80:
    grade = "A"
elif mark >= 65:
    grade = "B"
elif mark >= 50:
    grade = "C"
else:
    grade = "U"
print("Grade", grade)
if, elif and else. Input: 72. Notice that only one branch runs: the first condition that is True.

Output

Grade B
Run and checked before printing

Output

Cold
Mild
Mild
Hot
Run and checked before printing

Output

Charge: 3
Charge: 6
Charge: 6
Charge: 10
Run and checked before printing

Nested selection

Short code B8·8·15

username = input()
if username == "zara07":
    pin = int(input())
    if pin == 4321:
        print("Welcome back")
    else:
        print("Wrong PIN")
else:
    print("Unknown user")
Nested selection. Inputs: zara07, then 1234. Notice that the PIN is asked for only when the username is right.

Output

Wrong PIN
Run and checked before printing

match-case

Short code B8·8·16

day = int(input())
match day:
    case 6 | 7:
        print("Weekend")
    case 1 | 2 | 3 | 4 | 5:
        print("School day")
    case _:
        print("Not a day number")
match-case with several values in one case. Input: 6.

Output

Weekend
Run and checked before printing
choice = input()
match choice:
    case "A":
        print("Add a pupil")
    case "D":
        print("Delete a pupil")
    case "Q":
        print("Quit")
    case _:
        print("Invalid choice")
A menu with match-case. Input: d. Notice that case "D" does not match a lower-case d, so case _ runs.

Output

Invalid choice
Run and checked before printing

Count-controlled loops: for

Short code B8·8·17

number = int(input())
for i in range(1, 6):
    print(number, "x", i, "=", number * i)
A count-controlled loop. Input: 7. Notice that range(1, 6) stops at 5.

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Run and checked before printing

Output

0
1
2
3
4
--
2
3
4
5
--
1
4
7
--
10
8
6
4
2
Run and checked before printing

Pre-condition loops: while

Short code B8·8·18

age = int(input())
while age < 11 or age > 18:
    print("Age must be 11 to 18")
    age = int(input())
print("Accepted:", age)
A pre-condition loop that validates an input. Inputs: 25, 9, 15. Notice that the condition is tested before each turn: if the first age had been 15, the loop body would never have run.

Output

Age must be 11 to 18
Age must be 11 to 18
Accepted: 15
Run and checked before printing

Output

3 0
6 1
12 2
24 3
48 4
96 5
output: 96 5
Run and checked before printing

Output

Too short - at least 8 characters
Too short - at least 8 characters
Password accepted
Run and checked before printing

Output

Choose 1 to 6 tickets
Choose 1 to 6 tickets
Cost: 30.0
Run and checked before printing

Post-condition loops: while True and break

Short code B8·8·19

total = 0
while True:
    amount = float(input())
    total = total + amount
    more = input()
    if more == "no":
        break
print("Total to pay:", total)
A post-condition loop: while True with break. Inputs: 2.5, yes, 4.25, yes, 1.25, no. Notice that the body always runs at least once.

Output

Total to pay: 8.0
Run and checked before printing

Nested loops

Short code B8·8·20

for row in range(1, 4):
    line = ""
    for col in range(1, 5):
        line = line + str(row * col) + " "
    print(line)
Nested loops. Notice that the inner loop runs all four times for every one turn of the outer loop: 3 x 4 = 12 numbers.

Output

1 2 3 4
2 4 6 8
3 6 9 12
Run and checked before printing

Output

1 0 1
2 0 2
2 1 3
3 0 4
3 1 5
3 2 6
output: 6
Run and checked before printing

Totalling and counting

Short code B8·8·21

total = 0
count = 0
for day in range(7):
    rain = int(input())
    total = total + rain
    if rain > 10:
        count = count + 1
print("Total rainfall:", total)
print("Average:", total / 7)
print("Days over 10 mm:", count)
Totalling and counting together. Inputs: 4, 12, 0, 15, 7, 11, 7 (millimetres of rain on seven days).

Output

Total rainfall: 56
Average: 8.0
Days over 10 mm: 3
Run and checked before printing
total = 0
count = 0
highest = -1
score = int(input())
while score != -1:
    total = total + score
    count = count + 1
    if score > highest:
        highest = score
    score = int(input())
print("Scores entered:", count)
print("Average:", total / count)
print("Highest:", highest)
Totalling, counting and a highest value, with -1 to stop. Inputs: 14, 9, 20, 17, -1. Notice that the average divides by count, not by a fixed number.

Output

Scores entered: 4
Average: 15.0
Highest: 20
Run and checked before printing

Output

Total goals: 13
Matches with no goals: 4
Run and checked before printing

Output

Total sales: 12191
Months over 1000: 6
Run and checked before printing

String handling

Short code B8·8·22

place = "lahore fort"
print(len(place))
print(place.upper())
print(place.title())
print(place.find("fort"))
print(place.find("city"))
print(place.count("o"))
print(place.replace("fort", "museum"))
print(place[0])
print(place[-1])
print(place[0:6])
print(place + "!")
Every string method on the syllabus, run on one string. Notice that the first character is at index 0, and that .find() gives -1 when the text is not there.

Output

11
LAHORE FORT
Lahore Fort
7
-1
2
lahore museum
l
t
lahore
lahore fort!
Run and checked before printing
first = input()
family = input()
year = input()
username = first[0:3].lower() + family[0].upper() + year[2:4]
print("Username:", username)
print("Length:", len(username))
Building a username. Inputs: Hamza, Iqbal, 2011.

Output

Username: hamI11
Length: 6
Run and checked before printing

Output

0 b 0
1 a 1
2 n 1
3 a 2
4 n 2
5 a 3
output: 3
check: 3
Run and checked before printing

Output

9
AB-4471-X
2
ab/4471/x
Run and checked before printing

Output

3
The Cat Sat On The Mat
12
the cat sat on the mat!
Run and checked before printing

Arithmetic operators

Short code B8·8·23

print(17 + 5)
print(17 - 5)
print(17 * 5)
print(17 / 5)
print(17 // 5)
print(17 % 5)
print(2 ** 5)
print(20 / 4)
print(2 + 3 * 4)
print((2 + 3) * 4)
The arithmetic operators. Notice the three kinds of division: / gives a float, // the whole-number part, % the remainder.

Output

22
12
85
3.4
3
2
32
5.0
14
20
Run and checked before printing
minutes = int(input())
hours = minutes // 60
left = minutes % 60
print(hours, "hours and", left, "minutes")
if minutes % 2 == 0:
    print("an even number of minutes")
else:
    print("an odd number of minutes")
// and % at work. Input: 135.

Output

2 hours and 15 minutes
an odd number of minutes
Run and checked before printing

Output

4725 - 0
472 5 5
47 2 7
4 7 14
0 4 18
output: 18
Run and checked before printing

Relational and logical operators

Short code B8·8·24

a = 7
b = 10
print(a == b)
print(a != b)
print(a < b)
print(a >= 7)
print(a > 5 and b > 12)
print(a > 5 or b > 12)
print(not a > 5)
passed = b >= 10
print(passed)
Relational and logical operators. Notice that every comparison gives a Boolean: True or False.

Output

False
True
True
True
False
True
False
True
Run and checked before printing
mark = int(input())
if mark >= 0 and mark <= 100:
    print("Valid")
else:
    print("Invalid")
mark = int(input())
if not (mark < 0 or mark > 100):
    print("Valid")
else:
    print("Invalid")
A range check with and, and the same test written with not and or. Inputs: 104, then 104 again.

Output

Invalid
Invalid
Run and checked before printing
day = "Mon"
if day == "Sat" or "Sun":
    print("Weekend")
else:
    print("Weekday")
if day == "Sat" or day == "Sun":
    print("Weekend")
else:
    print("Weekday")
Meant to show a logic error: the second half of the or is not a comparison. The day is Mon, yet the program prints Weekend.

Output

Weekend
Weekday
Run and checked before printing

Command-word coach

Short code B8·8·25

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook: Programming fundamentals

Short code W8·8 · Algorithms, Programming and Databases Workbook

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Starter files

Short code W8·8·K

Data files and skeleton code in Python for this chapter's tasks arrive here with the chapter.

Ask Z about Programming fundamentals
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook