Type Conversions
Concepts covered: Type Conversion
Remember from the beginner lesson that every value has a type? An integer like 42 is different from a string like "42", even though they look similar. Sometimes you need to convert between these types.
Why Convert Between Types?
Data doesn't always arrive in the format you need. Here are common situations where type conversion is essential:
- User input: Always arrives as text, even when users type a number.
- Files (CSV, JSON): Store everything as text strings that need parsing into numbers.
- API responses: Return data as strings that your code must convert to usable types.
- Display output: Numbers must become strings before you can embed them in messages.
For example, if a user types "25" into an age field, your program receives the string "25", not the number 25. To check if they're old enough to vote, you need to convert that string to a number first.
The Conversion Functions
Python provides built-in functions that convert values from one type to another. Each function is named after the type it creates:
- int(): Whole numbers, truncates
- float(): Adds decimal precision
- str(): Text for display output
- bool(): True or False from value
int() - Convert to Integer
Takes a value and returns a whole number. It truncates decimal points instead of rounding, and can convert strings that contain only digits.
Converting a string to an integer:
user_input = "25"
age = int(user_input)
birth_year = 2024 - age
print(f"Age: {age}, Born: {birth_year}")Output:
Age: 25, Born: 1999
Now age contains the integer 25, not the string "25", so you can do math with it.
Converting a float to an integer removes the decimal part:
print(int(3.9))
print(int(3.1))
print(int(-2.7))Output:
3 3 -2
All three cut off the decimal portion. 3.9 becomes 3, not 4. This is truncation, not rounding.
float(): Convert to Decimal
Creates a decimal number from integers or strings. Useful when you need precision or when working with division results.
price_text = "19.99"
price = float(price_text)
print(price)
whole_number = 42
decimal_version = float(whole_number)
print(decimal_version)Output:
19.99 42.0
Now price is 19.99 (a number, not text). float(42) creates 42.0, useful when you need decimal behavior.
str() - Convert to String
Turns any value into its text representation. This is essential for displaying numbers in messages and required when combining text with numbers.
You can't concatenate strings with numbers directly. This causes an error:
message = "Found " + 42 + " items"Convert the number to text first:
message = "Found " + str(42) + " items"
print(message)Output:
Found 42 items
Now message contains "Found 42 items". The str() function converts 42 to the string "42" so concatenation works.
bool() - Convert to Boolean
Converts any value to True or False. Python follows specific rules about what counts as "truthy" versus "falsy", which you will use constantly in conditions.
Python has clear rules about what values become True and what become False:
print(bool(1))
print(bool(0))
print(bool(""))
print(bool("hello"))Output:
True False False True
1 becomes True, 0 becomes False. Empty string "" becomes False, but any non-empty string becomes True.
When Conversions Fail
Not all conversions are possible. What happens if you try to convert the word "hello" to a number? Python doesn't know what number "hello" should become, so it raises an error:
int("hello")
int("12.5")
float("abc")All three crash with ValueError. Notice int("12.5") also fails because int() can't parse decimals from text. You'd need float() first, then int().
The two-step conversion int(float(text)) is a common pattern when data arrives as a decimal string but you need a whole number. float() parses the decimal, then int() truncates it.
Chaining conversion functions like this is readable and explicit. Each conversion step has a clear purpose, making the intent obvious to anyone reading the code.
Now try selecting different conversion functions to see how Python transforms the same string value.
The fact that bool("False") returns True surprises many beginners. bool() checks whether a string is non-empty, not whether it spells out a true value.
Type conversion is a gateway skill. Once you can reliably move data between types, you can handle real-world inputs from files, APIs, and user prompts with confidence.
About this lesson
This section is part of the Python Expressions: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.