Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.1

Constructs and procedures in code

§11.1§11.2§11.3AS skills Paper 4 builds onBanker · ≈ 62.6 m · ↘B4·1

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

For the whole chapter

§11.1 Programming basics

Short code B4·1·1

§11.2 Constructs

Short code B4·1·2

§11.3 Structured programming

Short code B4·1·3

Your toolkit, in code

Short code B4·1·10

SEATS = 52              # constant: seats on one coach
Pupils = 130            # INTEGER
Full = Pupils // SEATS
LeftOver = Pupils % SEATS
Needed = Full
if LeftOver > 0:
    Needed = Needed + 1
print("Full coaches:", Full)
print("Pupils left over:", LeftOver)
print("Coaches needed:", Needed)
A constant, three variables and whole-number arithmetic: 130 pupils need 3 coaches, not 2.5.

Output

Full coaches: 2
Pupils left over: 26
Coaches needed: 3
Run and checked before printing

Part A: variables, constants and data types

Short code B4·1·11

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

Converting between types

Short code B4·1·12

Text = "42"             # STRING
Number = int(Text) + 8  # INTEGER
Whole = int(7.9)        # integer part, like INT(7.9)
Label = "Room " + str(12)
print(Number, Whole, Label)
print(ord("A"), chr(66))
Converting between types: text to a number, a number to text, a real to its whole-number part, a character to its code and back.

Output

50 7 Room 12
65 B
Run and checked before printing
Module Program
    Sub Main()
        Console.WriteLine(CInt(7.9))
        Console.WriteLine(CInt(Int(7.9)))
        Console.WriteLine(CInt(2.5) & " " & CInt(3.5))
    End Sub
End Module
VB.NET's CInt rounds; Int (or Fix) keeps the whole-number part. At exactly .5, CInt rounds to the even number.

Output

8
7
2 4
Run and checked before printing

Input and output

Short code B4·1·13

Name = input("Name: ")
Age = int(input("Age: "))
print("Hello " + Name + ", next year you will be " + str(Age + 1))
Prompt, input, convert, output. The inputs are Sara and 16: a run with typed input shows them, a checked run like this one does not, so each prompt runs straight into the next.

Output

Name: Age: Hello Sara, next year you will be 17
Run and checked before printing
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner In = new Scanner(System.in);
        System.out.print("Age: ");
        int Age = In.nextInt();
        System.out.print("Name: ");
        String Name = In.nextLine();
        System.out.println("[" + Name + "] is " + Age);
    }
}
nextInt() reads 16 but leaves the Enter key behind, so the next nextLine() returns an empty string at once. Inputs: 16, then Sara.

Output

Age: Name: [] is 16
Run and checked before printing

Arithmetic

Short code B4·1·14

A = 17
B = 5
print(A // B, A % B, A / B, 2 ** 10)
The arithmetic operators. Java's / between two integers is whole-number division, so it needs a real operand (17.0) to give 3.4.

Output

3 2 3.4 1024
Run and checked before printing
print(-7 // 2, -7 % 2)
Python: // rounds down, so −7 // 2 is −4, and % takes the sign of the divisor.

Output

-4 1
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        System.out.println((-7 / 2) + " " + (-7 % 2));
    }
}
Java (and VB.NET's \ and Mod): division truncates towards zero, so −7 / 2 is −3 and the remainder is −1.

Output

-3 -1
Run and checked before printing

Library routines: random numbers

Short code B4·1·15

import random

Lowest = 6
Highest = 1
Seen = [False] * 7
for Roll in range(1000):
    Dice = random.randint(1, 6)
    if Dice < Lowest:
        Lowest = Dice
    if Dice > Highest:
        Highest = Dice
    Seen[Dice] = True
AllSeen = Seen[1] and Seen[2] and Seen[3] and Seen[4] and Seen[5] and Seen[6]
if AllSeen:
    print(Lowest, Highest, "every face")
Random whole numbers from 1 to 6, rolled 1000 times. Each language writes the range differently, but all three give exactly 1 to 6, and every face turns up.

Output

1 6 every face
Run and checked before printing

String functions

Short code B4·1·16

City = "Karachi"
print(len(City))
print(City[2:5])          # MID(City, 3, 3)
print(City[-2:])          # RIGHT(City, 2)
print(City.upper())
print(City[0])            # first character
The guide's LENGTH, MID, RIGHT and UCASE in each language. MID(City, 3, 3) starts at the third character, which is index 2 in Python and Java.

Output

7
rac
hi
KARACHI
K
Run and checked before printing
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner In = new Scanner(System.in);
        String Pet = In.nextLine();
        if (Pet == "cat") {
            System.out.println("== says they match");
        } else {
            System.out.println("== says they differ");
        }
        if (Pet.equals("cat")) {
            System.out.println("equals says they match");
        }
    }
}
Java: == asks whether two strings are the same object; .equals() compares their characters. Input: cat.

Output

== says they differ
equals says they match
Run and checked before printing

Working through a string

Short code B4·1·17

Code = "Ab3 Cd45"
Digits = 0
Capitals = 0
for Index in range(len(Code)):
    Letter = Code[Index]
    if Letter >= "0" and Letter <= "9":
        Digits = Digits + 1
    elif Letter >= "A" and Letter <= "Z":
        Capitals = Capitals + 1
print(Digits, "digits,", Capitals, "capitals")
Visiting every character of a string with a count-controlled loop: digits and capital letters counted in one pass.

Output

3 digits, 2 capitals
Run and checked before printing
FullName = input("Full name: ")
Space = FullName.find(" ")
Initials = FullName[0] + FullName[Space + 1]
print(Initials.upper())
The Mark Ladder's model answer, run with the input Sara Malik.

Output

Full name: SM
Run and checked before printing
Module Program
    Sub Main()
        Console.Write("File name: ")
        Dim FileName As String = Console.ReadLine()
        Dim Dot As Integer = InStr(FileName, ".")
        Console.WriteLine(UCase(Mid(FileName, Dot + 1)))
    End Sub
End Module
The faded twin's model answer (file extension), run with the input notes.txt.

Output

File name: TXT
Run and checked before printing

Part B: selection with IF

Short code B4·1·18

Age = int(input("Age: "))
if Age < 0 or Age > 120:
    print("Invalid age")
elif Age < 12:
    print("Child")
elif Age < 18:
    print("Teen")
elif Age < 60:
    print("Adult")
else:
    print("Senior")
One IF with ELSE IF branches. Conditions are tested in order and only the first true branch runs. Input: 17.

Output

Age: Teen
Run and checked before printing

Selection with CASE

Short code B4·1·19

Choice = input("Choice: ").upper()
match Choice:
    case "A":
        print("Add a record")
    case "D":
        print("Delete a record")
    case "Q":
        print("Quit")
    case _:
        print("Unknown choice")
CASE in code: match (Python 3.10 or later; an if/elif/else chain is the safe Python answer), Select Case, switch. Each needs a branch for anything else. Input: d.

Output

Choice: Delete a record
Run and checked before printing
Module Program
    Function Floor(Room As Integer) As String
        Select Case Room
            Case 1 To 99
                Return "Ground"
            Case 100 To 199
                Return "First"
            Case 200, 201, 202
                Return "Roof office"
            Case Else
                Return "No such room"
        End Select
    End Function
    Sub Main()
        Console.WriteLine(Floor(42) & ", " & Floor(150) & ", " & Floor(201) & ", " & Floor(300))
    End Sub
End Module
VB.NET's Select Case also takes ranges (To), comparisons (Is) and lists. Java's switch matches exact values only, so a range needs an if chain there.

Output

Ground, First, Roof office, No such room
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        String Choice = "A";
        switch (Choice) {
            case "A":
                System.out.println("Add a record");
            case "D":
                System.out.println("Delete a record");
                break;
            default:
                System.out.println("Unknown choice");
        }
    }
}
The same switch with the first break left out. Input A runs its own branch, then falls through into the next one.

Output

Add a record
Delete a record
Run and checked before printing

Count-controlled loops

Short code B4·1·20

Total = 0
for Number in range(1, 10, 2):
    Total = Total + Number
print("Total", Total)
for Count in range(5, 0, -1):
    print(Count, end=" ")
print("Go")
Count-controlled loops counting up in steps of 2 and down in steps of −1. Python's range stops before its end value.

Output

Total 25
5 4 3 2 1 Go
Run and checked before printing

Pre-condition loops

Short code B4·1·21

Cells = 3
Hours = 0
while Cells <= 1000:
    Cells = Cells * 2
    Hours = Hours + 1
print(Hours, "hours,", Cells, "cells")
A pre-condition loop: the test comes first, so the body might never run. 3 cells doubling every hour pass 1000 after 9 hours.

Output

9 hours, 1536 cells
Run and checked before printing
Highest = -1000
Temp = int(input("Temperature: "))
while Temp != 999:
    if Temp > Highest:
        Highest = Temp
    Temp = int(input("Temperature: "))
print("Highest:", Highest)
The pre-condition Mark Ladder's model answer, run with the inputs 12, 31, −4 and 999.

Output

Temperature: Temperature: Temperature: Temperature: Highest: 31
Run and checked before printing
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner In = new Scanner(System.in);
        int Adults = 0;
        System.out.print("Age: ");
        int Age = Integer.parseInt(In.nextLine());
        while (Age != 0) {
            if (Age >= 18) {
                Adults = Adults + 1;
            }
            System.out.print("Age: ");
            Age = Integer.parseInt(In.nextLine());
        }
        System.out.println("Adults: " + Adults);
    }
}
The faded twin's model answer (adults counted), run with the inputs 15, 18, 40 and 0.

Output

Age: Age: Age: Age: Adults: 2
Run and checked before printing

Post-condition loops and validation

Short code B4·1·22

while True:
    Value = int(input("1 to 10: "))
    if Value >= 1 and Value <= 10:
        break
    print("Out of range")
print("Accepted", Value)
A post-condition loop for validation. Python has none, so while True with an if that runs break once the value is valid does the same job. Inputs: 0, 12, 7.

Output

1 to 10: Out of range
1 to 10: Out of range
1 to 10: Accepted 7
Run and checked before printing

Part C: procedures

Short code B4·1·23

def ShowLine(Length):          # procedure
    Line = ""
    for Count in range(Length):
        Line = Line + "-"
    print(Line)

def Area(Width, Height):       # function: returns INTEGER
    return Width * Height

ShowLine(10)
print("Area", Area(4, 5))
ShowLine(10)
A procedure (ShowLine) is called as a statement; a function (Area) returns a value that replaces the call in an expression.

Output

----------
Area 20
----------
Run and checked before printing

Functions and return values

Short code B4·1·24

def CountChar(Text, Letter):
    Count = 0
    for Index in range(len(Text)):
        if Text[Index] == Letter:
            Count = Count + 1
    return Count

print(CountChar("banana", "a"), CountChar("banana", "n"), CountChar("kiwi", "z"))
The function Mark Ladder's model answer, called three times.

Output

3 2 0
Run and checked before printing
Module Program
    Function CountDigits(Text As String) As Integer
        Dim Count As Integer = 0
        For Index As Integer = 1 To Len(Text)
            If Mid(Text, Index, 1) >= "0" And Mid(Text, Index, 1) <= "9" Then
                Count = Count + 1
            End If
        Next
        Return Count
    End Function

    Sub Main()
        Console.WriteLine(CountDigits("Room 101B") & " " & CountDigits("none"))
    End Sub
End Module
The faded twin's model answer (CountDigits), called twice.

Output

3 0
Run and checked before printing

By value and by reference

Short code B4·1·25

def AddBonus(Score, Marks):
    Score = Score + 5
    Marks[0] = Marks[0] + 5

Score = 10
Marks = [10, 20]
AddBonus(Score, Marks)
print(Score, Marks[0])
The same result in all three languages: the integer parameter is a copy, so Score stays 10; the array is shared, so Marks[0] becomes 15.

Output

10 15
Run and checked before printing
Module Program
    Sub Double1(ByVal N As Integer)
        N = N * 2
    End Sub

    Sub Double2(ByRef N As Integer)
        N = N * 2
    End Sub

    Sub Main()
        Dim Score As Integer = 50
        Double1(Score)
        Console.WriteLine("After ByVal: " & Score)
        Double2(Score)
        Console.WriteLine("After ByRef: " & Score)
    End Sub
End Module
VB.NET states the passing method in the header. Only the ByRef parameter changes the caller's variable.

Output

After ByVal: 50
After ByRef: 100
Run and checked before printing
def Reset(Values):
    Values = [0, 0, 0]

def Clear(Values):
    for Index in range(len(Values)):
        Values[Index] = 0

Scores = [5, 6, 7]
Reset(Scores)
print(Scores)
Clear(Scores)
print(Scores)
Python: giving a parameter a new value rebinds the local name only; changing an element changes the list the caller also names.

Output

[5, 6, 7]
[0, 0, 0]
Run and checked before printing

Sending back more than one result

Short code B4·1·26

def Order(Low, High):
    if Low > High:
        return High, Low
    return Low, High

First = 42
Second = 17
First, Second = Order(First, Second)
print(First, Second)
Sending two results back. VB.NET passes both parameters ByRef; Python returns two values; Java returns them in an array.

Output

17 42
Run and checked before printing

Local and global variables

Short code B4·1·27

Visitors = 0               # global INTEGER

def Welcome(Name):
    global Visitors
    Visitors = Visitors + 1
    Message = Name + " is visitor " + str(Visitors)   # local
    print(Message)

Welcome("Ali")
Welcome("Mona")
print("Total", Visitors)
A global counter and a local message. Python needs global to assign to a global; VB.NET declares it in the module, Java as a static field.

Output

Ali is visitor 1
Mona is visitor 2
Total 2
Run and checked before printing
Visitors = 0

def Welcome(Name):
    Visitors = Visitors + 1
    print(Name + " is visitor " + str(Visitors))

try:
    Welcome("Ali")
except UnboundLocalError:
    print("UnboundLocalError: Visitors is local and has no value yet")
The same function without global: the assignment makes Visitors local to the whole function, so reading it first fails.

Output

UnboundLocalError: Visitors is local and has no value yet
Run and checked before printing

Efficient code

Short code B4·1·28

Data = [17, 8, 42, 5, 30, 12, 9, 25]
Target = 42
Index = 0
Found = False
Comparisons = 0
while not Found and Index < len(Data):
    Comparisons = Comparisons + 1
    if Data[Index] == Target:
        Found = True
    else:
        Index = Index + 1
if Found:
    print("Found at index", Index, "after", Comparisons, "comparisons")
else:
    print("Not found")
Efficient code stops when the job is done: the conditional loop makes 3 comparisons to find 42, where a FOR loop over the whole array would make 8.

Output

Found at index 2 after 3 comparisons
Run and checked before printing

From a design to code

Short code B4·1·29

Number = int(input("Positive whole number: "))
while Number > 9:
    Total = 0
    while Number > 0:
        Total = Total + Number % 10
        Number = Number // 10
    Number = Total
print("Digital root:", Number)
The digital-root design in code: an outer pre-condition loop, an inner loop that adds the digits with whole-number division and remainder. Input: 9875.

Output

Positive whole number: Digital root: 2
Run and checked before printing

Workbook 4: Constructs and procedures in code

Short code W4·1 · Practical Programming Task Book

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 W4·1·K

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

Ask Z about Constructs and procedures in code
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook