Data type conversion
To understand this section, make sure you are already familiar with variables and data types and understand that variables can store different types of data, like strings, integers, and floats.
What is data type conversion?
Data type conversion means changing a value from one data type to another. In Python, this is often called “casting.” You might need to do this when you want to use a value in a different way than it was originally stored.
For example, when you use the input() function, Python always gives you a string (text), even if the user enters a number. If you want to use that number in a calculation, you need to convert it to an integer or a float.
Example:
age = input("How old are you? ") # age is a string, even if you type 25
print(age + 1) # This will cause an error!
Output (an error):
TypeError: can only concatenate str (not "int") to str
Try it:
To fix this, convert the string to an integer:
age = input("How old are you? ")
age = int(age) # Now age is an integer
print(age + 1) # This works!
Output:
How old are you? 20
21
Before you converted age to a numerical data type (in this case an int), you couldn’t use it in any calculations as number.
Try it:
Common Type Conversion Functions
Python provides simple functions to convert between types:
| Function | Converts to… | Example | Result |
|---|---|---|---|
int(x) |
Integer | int("42") |
42 |
float(x) |
Float | float("3.14") |
3.14 |
str(x) |
String | str(100) |
"100" |
bool(x) |
Boolean | bool("hello"), bool("") |
True, False |
Examples
String to Integer:
num_str = "10"
num = int(num_str)
print(num + 5) # Output: 15
Integer to String:
score = 99
message = "Your score is " + str(score)
print(message) # Output: Your score is 99
String to Float:
height_str = "1.75"
height = float(height_str)
print(height * 2) # Output: 3.5
Float to Integer (truncates decimals):
price = 3.99
whole_price = int(price)
print(whole_price) # Output: 3
Value format compatibility
One thing to note when attempting to convert data types, is that the value has to be in a format that is recognised by the conversion function.
For example
int("hello")
throws an error:
ValueError: invalid literal for int() with base 10: 'hello'
To prevent such errors occurring, it is often good practice to first check the formatting.
For example, to prevent the error above, you could first use the isdigit() function to check if the value is an integer before trying to convert it to an integer.
if "hello".isdigit():
## This will not be executed since isdigit() will test False
print(int("hello"))
else:
print("hello is not an integer")
Since "hello" is not a recognised string representation of an integer, isdigit() returns False and there is no conversion
hello is not an integer
if "1".isdigit():
## Conversion works since isdigit() tests True
print(int("1")) ## "1" is a recognised string representation of the integer 1
else:
print("1 is not an integer")
Since "1" is a recognised string representation of an integer, isdigit() returns True and the conversion works so the output is:
1
Modifying the user input code above, you can use isdigit() to validate user input (which is always a string data type) and then convert it to an integer data type if the string is in a format that is valid for conversion.
user_input = input("Enter an integer: ")
if user_input.isdigit():
number = int(user_input)
print(number * 2)
else:
print("That's not a valid number!")
Practice Exercises
Solidify your understanding of data type conversion with these exercises.
Q1: Convert string into float
Write a program that asks the user for a temperature in Celsius (as a number), converts it to Fahrenheit, and displays the result. The formula is: F = (C × 9/5) + 32
Expected output:
Enter temperature in Celsius: 25
25.0°C is 77.0°F
Enter temperature in Celsius: 0
0.0°C is 32.0°F
Example solution
celsius_str = input("Enter temperature in Celsius: ")
celsius = float(celsius_str)
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is {fahrenheit}°F")
Or all in one line:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is {fahrenheit}°F")
Q2: Validate input formatting
Write a program that asks the user for their birth year and calculates their age. Validate that the input is a valid integer before converting. If it’s not valid, print an error message.
Expected output:
Enter your birth year: 1995
You are approximately 30 years old
Enter your birth year: hello
That's not a valid year!
Example solution
birth_year_str = input("Enter your birth year: ")
if birth_year_str.isdigit():
birth_year = int(birth_year_str)
age = 2025 - birth_year
print(f"You are approximately {age} years old")
else:
print("That's not a valid year!")
