# Think like a programmer
FindTutor • Original practice pack • AS & A Level Computer Science

## Before you run anything
Trace each statement in order. Record variable values after assignments. For an IF, evaluate the condition using the current values. Python range(a, b) includes a and excludes b.

## Worked trace
```python
x = 3
for n in range(1, 4):
    x = x + n
print(x)
```
| n | x after addition |
|---|---|
| 1 | 4 |
| 2 | 6 |
| 3 | 9 |
Output: 9. The initial x = 3 is not overwritten at the start of each iteration.

## Six challenges
1. Trace the following. Write every output in order.
```python
for n in range(2, 7):
    if n % 2 == 0:
        print(n * 3)
```
2. A cinema admits someone if they are at least 15 OR they have adult permission. Write a function taking age and permission and returning a Boolean.
3. Write a function `largest(a, b, c)` that returns the largest argument without using max(), lists or sorting. Test a tie.
4. A PIN must contain exactly four decimal digits. Write `valid_pin(pin)` for a string input using a length check and a loop. Do not convert the PIN to an integer, because leading zeros matter.
5. Explain the error: `if choice == "Y" or "y":`. Correct it.
6. Write `is_prime(n)` for integer n. Return False for n < 2; test possible divisors. Explain why n = 1 is not prime.

## Answers and discussion
1. Outputs: **6, 12, 18**.
2.
```python
def allowed(age, permission):
    return age >= 15 or permission
```
3.
```python
def largest(a, b, c):
    result = a
    if b > result:
        result = b
    if c > result:
        result = c
    return result
# largest(4, 9, 9) returns 9
```
4.
```python
def valid_pin(pin):
    if len(pin) != 4:
        return False
    for char in pin:
        if char < "0" or char > "9":
            return False
    return True
# "0042": True; "123": False; "12a4": False
```
5. The non-empty string "y" is truthy, so the original condition always passes. Use `choice == "Y" or choice == "y"`.
6.
```python
def is_prime(n):
    if n < 2:
        return False
    divisor = 2
    while divisor * divisor <= n:
        if n % divisor == 0:
            return False
        divisor += 1
    return True
```
A prime has exactly two positive factors. 1 has only one. Any composite has a factor no greater than its square root, so the loop need not go further.

Python is used for practice. Translate into your exam board's required pseudocode conventions where appropriate. Not an official exam-board publication.
