Python distinguishes text, numbers and other value types.
The meaning of an operation depends on those types. Convert an input only when the intended meaning and invalid-input behaviour are clear.
Trace the value and its type
The literal '12' represents text; 12 represents an integer. With two strings, the + operator concatenates their characters, so '12' + '3' gives '123'. With two integers, + performs addition, so 12 + 3 gives 15. The operator symbol is the same, but the types determine the operation.
Use int(text) only when an integer is the intended meaning. int('twelve') raises ValueError because that text does not represent a valid integer. Converting an identifier such as '0012' also loses its leading zeros, which may be meaningful. A record number and an attendance count can both contain digits while needing different representations.
In the Python lab, run the original example, then replace one input with 'twelve'. Read the exception and identify the line that failed. Finally, try '0012' and decide whether conversion would be appropriate for a count and for a reference code. Your explanation should describe the meaning of the data as well as the syntax.
The bigger picture
A Python program transforms values according to explicit operations. To understand a program, trace the values and their types, not just the printed output. Text that looks like a number remains text until an operation converts it.
- Read inputs
- Trace operations
- Run code
- Test another case
Concepts to keep close
- Type
- The kind of value, which determines the operations that have meaning for it.
- Control flow
- The order in which statements execute, including branches and loops.
- Return value
- A result passed back to calling code; printing a result is a different action.
Reasoning through the problem
Inspect the input's type.
Decide whether arithmetic is intended.
Convert and check the result on a small example.
Use the idea carefully
Predict output before running a short example. Change one value or operation and explain the new result. Test an ordinary case, an empty input and a boundary. Read errors from the final exception message back to the relevant line. A passing example is evidence about that input, not proof that every possible input works.