Follow the data through a program
Think in three stages. Input is data the program receives, processing transforms that data, and output communicates the result. Start by underlining which pieces of a brief belong in each stage. In a calculator, receiving 5 and 3 is input, adding their integer values is processing, and displaying 8 is output.
input() reads one line and returns a string. The characters might look numeric, but Python has received text. Text "005" keeps both leading zeros, while int("005") gives the number 5. Choose the type that suits the job. You would add two quantities as numbers, but usually keep a locker label or a telephone number as text because the exact characters matter. A decimal measurement might use float, which can represent a fractional value. A Boolean stores True or False; comparisons later in the course produce those values.
Work through a conversion
boxes = input()
per_box = input()
total = int(boxes) * int(per_box)
print(total)
Supply 04 on the first line and 6 on the second. After the first read, boxes is the string "04". After the second, per_box is "6". The two calls to int produce 4 and 6, and the product is 24. If you move int() outside an addition, int(boxes + per_box) would first make the string "046" and then turn it into 46. Work out the order of operations before adding brackets.
Read errors and test deliberately
- If
int("cat")fails, the input exists but cannot be converted. Python reportsValueError.int("3.5")also fails. The requirement here is a whole number rather than a measurement. - If the program asks for three lines and you supply only two,
input()cannot read another line and reportsEOFError. A blank line can be a supplied value. It still fails if you immediately try to turn it into an integer. - Adding an integer to a string gives
TypeError. Check both operands. Use the variable names in the code and write down their types before fixing anything.
In the sandbox, set input lines first, then run. Try two normal cases, one involving zero and one with a negative number where the brief allows it. Calculate the expected answers on paper before checking the result. If the task requires exact output, an extra input("Enter a value: ") prompt can affect the comparison. The calculator exercises use plain input() for that reason.
Practise a Paper 2 habit
A provided file stores the cost in whole pounds and the number of tickets. Its output is 23 when the two inputs are 2 and 3, but the required result is 6. Explain the bug and repair it so the two input values are multiplied. Test 0 with 9 and 7 with 4. Then explain how you know the program used both inputs.