Getting Started with Python
Type conversion and debugging
Fix a program that gives '22' instead of 4.
A common surprise: a program asks for a number, the user types 2, and the program prints 22 instead of 4. Why? Because input() returns the string '2', and '2' * 2 repeats the string, giving '22'. Converting first, int('2') * 2, gives 4.
Explicit conversion (type casting) is done by the programmer, using functions:
- int(x) makes a whole number: int('42') is 42. It can lose information: int(9.99) is 9 (the fraction is dropped, not rounded).
- float(x) makes a decimal number: float('2.5') is 2.5.
- str(x) makes a string. You must use it to join a number to a string: 'Total: ' + str(250) works, but 'Total: ' + 250 gives an error.
- chr(x) gives the character for a code: chr(66) is 'B'.
- ord(x) gives the code for a character: ord('B') is 66.
Implicit conversion (coercion) is done by Python itself. In 5 + 2.5, Python changes 5 into 5.0 and gives 7.5, a float. It always converts to the wider type, so that no information is lost.
Debugging means finding and removing errors (bugs). There are three kinds:
- Syntax errors break the rules of the language, like a missing bracket in print(7 + 11. The program does not run at all.
- Logical (semantic) errors let the program run, but give the wrong output. To average 10 and 12, writing 10 + 12 / 2 gives 16.0; the right expression is (10 + 12) / 2, giving 11.0.
- Runtime errors stop a program that looked fine, while it is running: for example, dividing by zero, or int() given text that is not a number.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.