First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Software programming
In a Python program, which data type would you choose to store whether a light switch is currently on or off?
- String
- Integer
- Float
- Boolean Correct answer.
Explanation
A Boolean holds one of two truth values, True or False, which maps directly onto an on/off state. Integers, strings and floats can represent other values but carry no built-in two-state meaning.
Question 2Software programming
A programmer writes the Python line `total = 5 + 3 * 2`. What value is stored in `total`?
- 30
- 11 Correct answer.
- 13
- 16
Explanation
Multiplication is evaluated before addition because it has higher operator precedence, so 3 * 2 is computed first to give 6, then 5 + 6 gives 11. Brackets would be needed to force the addition first.
Question 3Software programming
Which Python statement correctly reads a whole number typed by the user into a variable named `age`?
- int age = input("Age: ")
- age = input("Age: ") as int
- age = int(input("Age: ")) Correct answer.
- age = input(int)
Explanation
`input()` always returns a string, so it must be wrapped in `int()` to convert the typed text into a whole number. The conversion function goes around the input call, not the other way round.
Question 4Software programming
What is the main purpose of a variable in a program?
- To describe the output format shown to the user
- To permanently fix a value that can never be altered
- To name a storage location whose value can change while the program runs Correct answer.
- To translate source code into machine code
Explanation
A variable is a named reference to a stored value, and that value can be reassigned during execution. Constants, not variables, are the construct intended to hold values that should not change.
Question 5Software programming
A program uses the loop `for i in range(3):`. How many times does the loop body run?
- 3 Correct answer.
- 4
- It runs forever
- 2
Explanation
`range(3)` produces the sequence 0, 1, 2, which contains three values, so the body executes three times. The upper bound is excluded, which is why it is not four.
Question 6Software programming
What does the `if` statement allow a program to do?
- Choose whether to run a block based on a condition Correct answer.
- Define a reusable block of code with a name
- Repeat a block of code a fixed number of times
- Store a list of related values
Explanation
An `if` statement evaluates a condition and runs its block only when that condition is true, giving the program a decision point. Repetition, collections and named reusable blocks are handled by other constructs.
Question 7Software programming
Which of these is a valid, well-formed Python function definition?
- define greet():
- def greet[]:
- def greet(): Correct answer.
- function greet():
Explanation
Python function definitions begin with the keyword `def`, followed by the name, parentheses and a colon. The other spellings borrow keywords or bracket styles that Python does not use for definitions.
Question 8Software programming
A list in Python is created as `scores = [12, 8, 15]`. What does `scores[1]` return?
- 8 Correct answer.
- 15
- 12
- An error, because lists start at 1
Explanation
Python lists are indexed from zero, so index 0 holds 12, index 1 holds 8 and index 2 holds 15. Accessing index 1 therefore returns the second element.
Question 9Software programming
What is the output of this code?
```
x = 4
x = x + 3
print(x)
```
- 3
- 7 Correct answer.
- x + 3
- 4
Explanation
The second line reads the current value of `x` (4), adds 3 to give 7, and stores that back into `x`. The print then displays the new value, 7.
Question 10Software programming
A program must run a block of code repeatedly until the user enters the word "stop". Which loop structure suits this best?
- A function definition without a loop
- A single `if` statement
- A `while` loop that checks the input each iteration Correct answer.
- A `for` loop over `range(10)`
Explanation
The number of repetitions is unknown in advance and depends on user input, so a condition-controlled `while` loop is appropriate because it re-tests the condition each pass. A counted `for` loop needs a known count up front.
Question 11Software programming
What does the expression `not (a > b)` evaluate to when `a` is 5 and `b` is 9?
- 5
- 9
- True Correct answer.
- False
Explanation
With a = 5 and b = 9, the comparison `a > b` is False, and `not False` is True. The `not` operator inverts the Boolean result of the comparison.
Question 12Software programming
A programmer writes a function that takes two numbers and should return their average. Which return statement is correct?
- return (a + b) / 2 Correct answer.
- return a + b
- print((a + b) / 2)
- return a + b / 2
Explanation
The sum must be bracketed before dividing, otherwise only `b` is halved. Using `return` also sends the value back to the caller, whereas `print` only displays it.
Question 13Software programming
What is the purpose of a comment in source code, such as `# calculate the total`?
- To make the program run faster
- To declare a new variable
- To explain the code for human readers without affecting execution Correct answer.
- To stop the line from being run by the interpreter
Explanation
Comments are ignored by the interpreter and exist to document intent for people reading the code. They have no effect on speed, variables or output.
Question 14Software programming
A loop is written as:
```
total = 0
for n in [2, 4, 6]:
total = total + n
```
What is `total` after the loop finishes?
- 0
- 12 Correct answer.
- 6
- 2
Explanation
The loop adds each list value to the running total: 0 + 2 = 2, then 2 + 4 = 6, then 6 + 6 = 12. The accumulator pattern therefore ends at 12.
Question 15Software programming
Which comparison correctly tests whether two values `x` and `y` are equal in Python?
- x == y Correct answer.
- x != y
- x = y
- x equals y
Explanation
A double equals sign `==` is the equality comparison operator and yields True or False. A single `=` performs assignment rather than comparison.
Question 16Software programming
A programmer wants to store a student's name and age together as one record and access the age by a label. Which structure is most suitable?
- A list containing only the name
- A dictionary with keys such as "name" and "age" Correct answer.
- A Boolean
- A single integer
Explanation
A dictionary maps named keys to values, so `student["age"]` retrieves the age by label. This suits a record of related fields better than a single scalar value.
Question 17Software programming
What happens when a program tries to convert the string "abc" with `int("abc")`?
- It raises a ValueError Correct answer.
- It returns None
- It returns 0
- It returns the string unchanged
Explanation
`int()` can only convert text that represents a valid whole number, so letters fail the conversion and Python raises a ValueError. The program must handle this with a try/except or by validating input first.
Question 18Software programming
A program contains an `if`/`elif`/`else` chain. How many of the branches can run in a single pass through the chain?
- All of them
- Exactly one Correct answer.
- None of them, unless a loop is present
- At least two
Explanation
An `if`/`elif`/`else` chain tests conditions in order and executes the first branch whose condition is true, skipping the rest. If no condition is true, the `else` branch runs, so exactly one branch executes.
Question 19Software programming
Which statement about local and global variables is correct?
- A variable created inside a function is local to that function by default Correct answer.
- A local variable can be read anywhere in the program
- Local variables must be declared with the `global` keyword
- Global variables cannot be created in Python
Explanation
By default, a name assigned inside a function exists only within that function's scope and disappears when the call ends. Global variables are those defined at module level and are visible more widely.
Question 20Software programming
A function is defined as `def area(w, h):` and called with `area(3, 4)`. What are the values of `w` and `h` inside the function?
- w = 3, h = 4 Correct answer.
- w = 4, h = 4
- w = 4, h = 3
- w = 3, h = 3
Explanation
Arguments are matched to parameters by position, so the first argument 3 binds to the first parameter w and the second argument 4 binds to h. Order matters when arguments are passed positionally.
Question 21Software programming
A programmer writes a loop that never changes the variable used in its `while` condition. What is the likely result?
- The loop is skipped entirely
- The loop runs once and stops
- The loop runs an infinite number of times Correct answer.
- The loop raises a ValueError
Explanation
A `while` loop repeats as long as its condition stays true; if nothing inside the loop changes that condition, it remains true forever, producing an infinite loop. The condition variable must be updated each iteration.
Question 22Software programming
Consider this code:
```
nums = [3, 7, 2, 9]
result = 0
for n in nums:
if n > result:
result = n
```
What does `result` hold at the end?
- 3
- 9 Correct answer.
- 2
- 21
Explanation
The loop keeps the largest value seen so far: 3, then 7, then 7 (2 is not greater), then 9. This is the maximum-finding pattern, so the final value is 9.
Question 23Software programming
A function is meant to swap two variables `a` and `b` using a helper, but after the call the caller's values are unchanged. Which explanation is most consistent with Python's behaviour?
- The function must use the `global` keyword on every variable
- Python does not allow two variables to be swapped
- The function received copies of the values, so reassigning its parameters did not affect the caller's variables Correct answer.
- The `return` statement erases all changes made inside a function
Explanation
Rebinding a parameter inside a function only changes the local name; it does not reach back and change the caller's variable. To swap in the caller, the function must return the new values and the caller must assign them.
Question 24Software programming
A program validates a password and contains the condition `len(pw) >= 8 and pw != "password"`. Which pair of inputs makes the whole condition True?
- pw = "secret12" and pw = "longenough" Correct answer.
- pw = "abc" and pw = "secret12"
- pw = "password" and pw = "longenough"
- pw = "abc" and pw = "password"
Explanation
The `and` operator requires both parts to be true, so the password must be at least 8 characters and must not equal "password". Both "secret12" and "longenough" satisfy both tests.
Question 25Software programming
A program stores marks in a list and must count how many marks are 50 or above. Which approach correctly implements this?
- Set a counter to 0 and add each mark to it
- Set a counter to 0, loop over the list, and add 1 to the counter each time a mark is 50 or above Correct answer.
- Sort the list and print the first element
- Loop over the list and print each mark
Explanation
Counting requires an accumulator initialised to 0 and a conditional increment inside a loop, so only qualifying marks increase the count. Simply summing or printing the marks does not produce a count of those meeting the threshold.
Question 26Software programming
In Python, which data type would a programmer choose to store whether a light switch is on or off?
- String
- Boolean Correct answer.
- Float
- List
Explanation
A Boolean holds exactly one of two truth values, True or False, which maps directly onto an on/off state. Strings hold text, floats hold decimal numbers, and lists hold collections, so none of them represent a two-state flag as clearly.
Question 27Software programming
A program stores a product name in a variable. Which line correctly assigns the text value to the variable `product`?
- product := USB cable
- "USB cable" = product
- product == "USB cable"
- product = "USB cable" Correct answer.
Explanation
Assignment uses a single equals sign, and text values must be enclosed in quotation marks so Python treats them as a string literal. The other forms either test equality, reverse the operand order, or leave the text unquoted.
Question 28Software programming
A programmer wants to join a list of words into one string separated by spaces. Which Python approach does this?
- words.split(" ")
- str(words)
- words.join(" ")
- " ".join(words) Correct answer.
Explanation
The join method belongs to the separator string and takes the list of words as its argument, producing one combined string. Calling join on the list itself is not valid, split does the reverse operation, and str on a list produces a bracketed representation.
Question 29Software programming
Which Python operator gives the remainder after division, such as finding whether a number is even?
- //
- /
- **
- % Correct answer.
Explanation
The percent sign is the modulo operator and returns the remainder of a division, so `n % 2` yields 0 for even numbers. The other operators give floor division, exponentiation, and true division respectively.
Question 30Software programming
What does the built-in `len` function return when applied to a string such as `len("network")`?
- A Boolean showing whether the string is empty
- The number of characters in the string, which is 7 Correct answer.
- The string written backwards
- The first character of the string, which is "n"
Explanation
For a string, len counts the individual characters and returns that count as an integer. It does not extract characters, reverse text, or test emptiness; those require indexing, slicing, or a comparison.
Question 31Software programming
A program uses `while True:` with a `break` statement inside. What is the effect of the `break`?
- It skips the rest of the current iteration only
- It exits the loop immediately and continues with the code after the loop Correct answer.
- It restarts the loop from the first line of the body
- It pauses the program until the user presses a key
Explanation
The break statement ends the nearest enclosing loop at once, so control moves to the first statement after the loop. Skipping one iteration is the job of continue, and there is no restart or pause behaviour attached to break.
Question 32Software programming
A function is defined with a default parameter as `def greet(name="friend"):`. What happens when the function is called as `greet()`?
- It runs with name set to an empty string
- It raises an error because an argument is missing
- It runs twice, once for each possible value
- It runs with name set to "friend" Correct answer.
Explanation
A default value is used whenever the caller does not supply that argument, so name takes the string "friend". Defaults exist precisely to make an argument optional, and the function still runs only once per call.
Question 33Software programming
Which Python statement correctly opens a text file for reading and closes it automatically when the block ends?
- with open("data.txt", "w") as f:
- with open("data.txt", "r") as f: Correct answer.
- open("data.txt", "r") as f:
- f = open("data.txt") always
Explanation
The with statement combined with open in read mode creates a context manager that closes the file when the block finishes. The write mode would truncate the file, and the other forms are either incomplete or do not guarantee closing.
Question 34Software programming
A program has the list `temps = [18, 21, 25]` and runs `temps.append(19)`. What is the length of `temps` afterwards?
- 4 Correct answer.
- 5
- 2
- 3
Explanation
The append method adds one element to the end of the list, so the original three items become four. Length is unchanged only if no element is added, and the list cannot shrink through append.
Question 35Software programming
What is printed by this code?
```
word = "tablet"
print(word[1:4])
```
- abl Correct answer.
- blet
- tab
- abl e
Explanation
Slicing takes characters from the start index up to but not including the end index, so positions 1, 2 and 3 are taken. Position 0 is skipped and position 4 is excluded, giving three characters.
Question 36Software programming
A program contains:
```
count = 0
for ch in "banana":
if ch == "a":
count += 1
```
What is `count` at the end?
- 6
- 3 Correct answer.
- 2
- 1
Explanation
The loop adds one for every character equal to the letter a. The word banana contains three such letters, so the counter finishes at three.
Question 37Software programming
Which expression correctly tests that a score is at least 50 and below 80?
- score >= 50 and score < 80 Correct answer.
- score >= 50 and score <= 80
- score >= 50 or score < 80
- score > 50 and score < 80
Explanation
The lower bound must be inclusive for at least 50, and the upper bound must be exclusive so 80 itself is excluded. Using or would accept almost every number, and the other bounds shift one edge.
Question 38Software programming
A function is written as:
```
def double(n):
print(n * 2)
```
A programmer writes `result = double(5)` and then prints `result`. What is shown?
- 0
- None Correct answer.
- 10
- An error about a missing return
Explanation
The function prints the doubled value but never uses return, so the call evaluates to None. The value 10 appears on screen from inside the function, yet the assigned variable receives None.
Question 39Software programming
A list of marks is stored as `marks = [45, 72, 38, 90]`. Which built-in call returns the highest mark?
- marks.sort()
- sum(marks)
- max(marks) Correct answer.
- min(marks)
Explanation
The max function scans an iterable and returns its largest element, which is 90 here. The min and sum functions give the smallest value and the total, and sort rearranges the list rather than returning a single value.
Question 40Software programming
A programmer writes:
```
n = 0
while n < 3:
print(n)
```
What is the main problem with this loop?
- The condition is false at the start, so the body never runs
- The print statement cannot display an integer
- The variable n is never changed, so the loop runs forever Correct answer.
- The loop will run exactly three times and then stop
Explanation
A while loop repeats only while its condition stays true, so the body must change the variable used in that condition. Since n stays at 0, the condition remains true indefinitely and the program never exits.
Question 41Software programming
Given `data = {"name": "Aroha", "year": 13}`, which expression retrieves the value 13?
- data[1]
- data[13]
- data["year"] Correct answer.
- data.year
Explanation
A dictionary is accessed by its key, so the key "year" returns the associated value 13. Positional indexing does not apply to dictionaries, dot notation is not the standard lookup, and using 13 as a key looks in the wrong direction.
Question 42Software programming
A program must keep asking for a number until the user enters a value that converts successfully. Which approach handles invalid text input without crashing?
- Store the input in a list and convert the whole list at the end
- Convert with int inside the loop and let the program stop on bad input
- Wrap the conversion in try and except and repeat the prompt when a ValueError occurs Correct answer.
- Compare the raw input to numbers using the greater than operator
Explanation
Invalid text raises a ValueError during conversion, so a try block with an except clause lets the program catch that error and prompt again. Letting the error escape ends the program, and comparing or converting later does not prevent the failure.
Question 43Software programming
A function is defined as:
```
def total(items):
result = 0
for i in items:
result += i
return result
```
What does `total([4, 5, 6])` return?
- 456
- 0
- 3
- 15 Correct answer.
Explanation
The loop adds each element of the list to the running total, so 4 plus 5 plus 6 gives 15. The variable result starts at 0 and accumulates the numeric values rather than joining text or counting items.
Question 44Software programming
A programmer wants to store the names of students in a fixed order and later access the third student by position. Which structure is most suitable?
- A list, because items keep their order and can be accessed by index Correct answer.
- A single string, because names are text
- A dictionary, because keys can be any text
- A Boolean, because it records whether a student exists
Explanation
A list preserves insertion order and supports positional indexing, so the third student is retrieved with index 2. A dictionary is organised by keys rather than position, a Boolean holds only two states, and one string cannot hold separate named entries cleanly.
Question 45Software programming
A program contains:
```
values = [1, 2, 3, 4, 5]
out = []
for v in values:
if v % 2 == 0:
out.append(v * 10)
```
What is the final contents of `out`?
- [1, 2, 3, 4, 5]
- [10, 30, 50]
- [2, 4]
- [20, 40] Correct answer.
Explanation
The condition keeps only even values, which are 2 and 4, and each is multiplied by ten before being appended. The result therefore holds 20 and 40 in the order the even values appeared.
Question 46Software programming
A function is meant to return the average of a list but is written as:
```
def avg(nums):
return sum(nums) / len(nums)
```
What happens when it is called with an empty list?
- It returns 0 because the sum of an empty list is 0
- It returns None because the list has no items
- It returns an empty list
- A ZeroDivisionError is raised because the length is zero Correct answer.
Explanation
The sum of an empty list is 0, but len returns 0 as well, and dividing by zero raises a ZeroDivisionError in Python. The function does not guard against this case, so the error propagates to the caller.
Question 47Software programming
Consider:
```
def change(items):
items.append(9)
nums = [1, 2]
change(nums)
print(nums)
```
What is printed and why?
- [1, 2], because the function works on a copy of the list
- [9], because append replaces the list contents
- An error, because lists cannot be passed to functions
- [1, 2, 9], because the list object is shared and mutated in place Correct answer.
Explanation
Lists are mutable objects passed by reference, so append modifies the same list the caller holds. No copy is made, and append adds to the existing contents rather than replacing them.
Question 48Software programming
A programmer needs a loop that prints the numbers 5, 4, 3, 2, 1 in that order. Which loop header produces exactly this sequence?
- for n in range(5, 1, -1):
- for n in range(5, 0, -1): Correct answer.
- for n in range(1, 6):
- for n in range(5, 0):
Explanation
The range function takes start, stop and step, where stop is exclusive and the step of -1 counts down. Starting at 5 and stopping before 0 with a negative step yields 5 through 1 inclusive.
Question 49Software programming
A program validates input with `age = int(raw) if raw.isdigit() else -1`. A tester enters "07". What value does `age` hold?
- -1
- An error is raised
- 7 Correct answer.
- "07"
Explanation
The isdigit method returns true for "07" because every character is a digit, so the conversion runs and int("07") evaluates to the integer 7. Leading zeros are dropped during conversion, and no error occurs.
Question 50Software programming
A function is defined as:
```
def f(x):
if x < 0:
return "neg"
if x == 0:
return "zero"
return "pos"
```
Which input returns "pos"?
- -3
- -0.5
- 7 Correct answer.
- 0
Explanation
A positive number fails both earlier conditions, so execution reaches the final return and yields "pos". Zero matches the equality test, and negative values match the first test.