Computer Science · Ch 5 — Getting Started with Python
Type Conversion
Type Conversion
Sometimes the data type a value arrives in is not the type our calculation needs. Type conversion is the changing of a variable's data type from one type to another — and a small program shows exactly why it matters.
A program that goes wrong
Consider this program, which is meant to read a number and double it:
num1 = input("Enter a number and I'll double it: ")
num1 = num1 * 2
print(num1)
If the user enters 2, we expect the output 4. But the program actually displays:
Enter a number and I'll double it: 2
22
Why 22? Because the value returned by input() is a string by default — the user's 2 arrives as "2". In the statement num1 = num1 * 2, num1 therefore holds a string value, and for a string the * operator is the repetition operator (Section 5.8.1). The string "2" repeated twice is "22".
The fix: convert the type
To get 4, we must convert the data type of the value entered by the user to an integer before multiplying:
num1 = input("Enter a number and I'll double it: ")
num1 = int(num1) # convert string input to integer
num1 = num1 * 2
print(num1)
Now the program behaves as intended:
Enter a number and I'll double it: 2
4
Two ways type conversion can happen
As and when required, we can change the data type of a variable in Python from one type to another. Such conversion happens in two ways:
- Explicitly (forced) — the programmer instructs the interpreter to convert a data type into another type, as we did with
int(num1)above. This is covered in Section 5.12.1. …