Book 4 · Chapter P4.1
Constructs and procedures in code
B4·1This 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.
For the whole chapter
- Topic pageProgramming
B4·1·T - QuizProgramming (9618 Paper 2)
B4·1·Q1 - LabProgramming tasks (auto-marked)
B4·1·X1 - LabPaper 4 Python, step by step
B4·1·X2 - LabPseudocode Playground
B4·1·X3 - LabTranslate to Python / VB / Java
B4·1·X4
§11.1 Programming basics
Short code B4·1·1
- FlashcardsFlashcards §11.1: Programming basics & 9618 pseudocode
B4·1·F1 - Past-paper questionsPast-paper questions §11.1 (programming-basics)
B4·1·1
§11.2 Constructs
Short code B4·1·2
- FlashcardsFlashcards §11.2: Selection & iteration constructs
B4·1·F2 - Past-paper questionsPast-paper questions §11.2 (constructs)
B4·1·2
§11.3 Structured programming
Short code B4·1·3
- FlashcardsFlashcards §11.3: Structured programming — procedures, functions, parameters
B4·1·F3 - Past-paper questionsPast-paper questions §11.3 (structured-programming)
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)Output
Full coaches: 2 Pupils left over: 26 Coaches needed: 3
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))Output
50 7 Room 12 65 B
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 ModuleCInt rounds; Int (or Fix) keeps the whole-number part. At exactly .5, CInt rounds to the even number.Output
8 7 2 4
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))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
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
Arithmetic
Short code B4·1·14
A = 17
B = 5
print(A // B, A % B, A / B, 2 ** 10)/ 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
print(-7 // 2, -7 % 2)// rounds down, so −7 // 2 is −4, and % takes the sign of the divisor.Output
-4 1
public class Main {
public static void main(String[] args) {
System.out.println((-7 / 2) + " " + (-7 % 2));
}
}\ and Mod): division truncates towards zero, so −7 / 2 is −3 and the remainder is −1.Output
-3 -1
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")Output
1 6 every face
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 characterOutput
7 rac hi KARACHI K
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");
}
}
}== asks whether two strings are the same object; .equals() compares their characters. Input: cat.Output
== says they differ equals says they match
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")Output
3 digits, 2 capitals
FullName = input("Full name: ")
Space = FullName.find(" ")
Initials = FullName[0] + FullName[Space + 1]
print(Initials.upper())Sara Malik.Output
Full name: SM
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 Modulenotes.txt.Output
File name: TXT
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")17.Output
Age: Teen
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")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
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 ModuleSelect 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
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");
}
}
}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
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")range stops before its end value.Output
Total 25 5 4 3 2 1 Go
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")Output
9 hours, 1536 cells
Highest = -1000
Temp = int(input("Temperature: "))
while Temp != 999:
if Temp > Highest:
Highest = Temp
Temp = int(input("Temperature: "))
print("Highest:", Highest)Output
Temperature: Temperature: Temperature: Temperature: Highest: 31
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);
}
}Output
Age: Age: Age: Age: Adults: 2
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)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
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)ShowLine) is called as a statement; a function (Area) returns a value that replaces the call in an expression.Output
---------- Area 20 ----------
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"))Output
3 2 0
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 ModuleCountDigits), called twice.Output
3 0
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])Score stays 10; the array is shared, so Marks[0] becomes 15.Output
10 15
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 ModuleByRef parameter changes the caller's variable.Output
After ByVal: 50 After ByRef: 100
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)Output
[5, 6, 7] [0, 0, 0]
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)ByRef; Python returns two values; Java returns them in an array.Output
17 42
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)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
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")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
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")Output
Found at index 2 after 3 comparisons
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)9875.Output
Positive whole number: Digital root: 2
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.


