Type Conversion
PronunciationTYPE kun-VER-zhun
Definition
Type conversion changes a value from one type to another, for example turning the text "42" into the number 42.
Where you hear it
When reading user input or files, parsing data from an API, and in error messages such as ValueError.
Examples
Input arrives as text, so convert it to an integer before adding.
The conversion fails if the text is not a valid number.
int('42') + 1 gives 43, because the text is converted to a number first.
Common mistake
Converting without handling bad input. int("abc") raises an error, so validate or catch it.
Don't confuse with
Type checking, which asks what type a value has. Conversion actually changes it into another type.
Say it at work
- In a meeting or chat
Cast the query parameter to an integer before using it.
- In an email or ticket
Wrap the conversion in a try block in case the value is not numeric.
Keep exploring
More in Programming Fundamentals