Python Type Conversion: How to Convert Between Data Types
Imagine you ask someone their age and they write it on a sticky note. You now have the text "25" — but you can't do math with a sticky note. You need to read the text and turn it into an actual number in your head first.
Python works the same way. Data often arrives in one type but needs to be another. A user types "42" into a form — that's a string, not a number. Before you can add, subtract, or compare it, you need to convert it.
This tutorial teaches you how to convert between Python's data types safely and confidently. You'll learn which conversions happen automatically, which ones you need to do yourself, and how to avoid the errors that trip up beginners.
What Is Type Conversion in Python?
Type conversion means changing a value from one data type to another. For example, turning the string "42" into the integer 42, or turning the integer 10 into the float 10.0.
Python has two kinds of type conversion. Implicit conversion happens automatically — Python does it for you behind the scenes. Explicit conversion is when you use a function like int() or str() to convert a value yourself.
Think of implicit conversion like your phone auto-correcting a word. Explicit conversion is like manually editing the word yourself. Both get the job done, but you have more control with the manual approach.
How Python Implicit Type Conversion Works
When you mix an integer and a float in a math operation, Python automatically converts the integer to a float. This is called implicit conversion (or type coercion). Python always converts to the "wider" type so no data is lost.
It's like pouring water from a small cup into a big bucket. The water (your data) stays the same — it just lives in a bigger container now. Going from int to float is safe because a float can hold any integer value.
How to Convert to Integer with int()
The int() function converts a value to an integer. You can convert floats, strings, and booleans. Each type behaves a little differently.
Converting Floats to Integers
When you convert a float to an integer, Python truncates — it chops off everything after the decimal point. It does not round. Think of it like cutting a rope: whatever hangs past the mark just falls away.
Converting Strings to Integers
You can convert a string to an integer only if the string contains a valid whole number. Spaces around the number are fine, but decimal points or letters will cause an error.
How to Convert to Float with float()
The float() function converts a value to a floating-point number. It handles integers, strings, and booleans.
Converting an integer to a float is always safe. Nothing is lost — the number just gets a .0 added to the end. It's like adding extra decimal places to a price: $5 becomes $5.00.
How to Convert to String with str()
The str() function converts any value into its string representation. This is the most forgiving conversion function — it works on almost everything.
You'll use str() most often when building messages that mix text and numbers. Python won't let you glue a string and a number together with +, so you convert the number to a string first.
name = "Alice"
age = 25
print("Name: " + name + ", Age: " + str(age))name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")How to Convert to Boolean with bool()
The bool() function converts a value to True or False. The rule is simple: empty and zero values are `False`, everything else is `True`.
Think of it like asking "is there anything here?" An empty box is False. A box with something in it — even just a crumpled piece of paper — is True.
Common Type Conversion Errors in Python
Not every conversion is possible. When Python can't convert a value, it raises a ValueError. This is the most common error beginners hit when working with type conversion.
It's like trying to translate a word that doesn't exist in the other language. Python looks at the value, tries to convert it, and says "I have no idea how to turn this into a number."
| Here's a quick reference of what works and what doesn't: | ||
|---|---|---|
| --- | --- | --- |
int("42") | String of digits | 42 |
int("3.14") | String with decimal | ValueError |
int("hello") | Non-numeric string | ValueError |
float("3.14") | String with decimal | 3.14 |
float("abc") | Non-numeric string | ValueError |
int(float("3.14")) | Two-step conversion | 3 |
How to Safely Convert Types in Python
In real programs, you often get data from users or files. You can't always trust that the data is a valid number. If you just call int() on bad input, your program crashes.
Python gives you two ways to handle this safely. You can check before converting with methods like .isdigit(), or you can try and catch the error with try/except.
Checking First with .isdigit()
The .isdigit() method returns True if every character in a string is a digit. It's a quick way to check if a string can be safely converted to an integer.
Using try/except for Safe Conversion
The try/except pattern is the most flexible way to handle conversions. You attempt the conversion, and if it fails, you catch the error and do something else. You'll learn try/except in depth later — for now, here's the basic pattern.
Practice Exercises
Time to put your type conversion skills to the test. These exercises start easy and build up. Try each one before looking at the hints.
You have a string variable text containing "42". Convert it to an integer and multiply by 2. Print the result.
Expected output:
84You have a float price = 9.99. Convert it to an integer and print both the original and converted values to show what gets lost.
Expected output:
Original: 9.99
Converted: 9
Lost: 0.99Hint: calculate what was lost by subtracting. Use round() on the lost amount to avoid floating-point weirdness.
Without running the code, predict what each line will print. Write your predictions as comments, then run it to check.
Think carefully about truncation, string conversion, and truthy/falsy rules.
This code tries to build a message, but it crashes with a TypeError. Fix it so it prints:
You have 3 new messagesYou can fix it any way you like (str(), f-strings, etc.).
Write code that checks three strings using .isdigit() and converts them to integers only if safe. For each string, print either the converted number or "Not a number".
Given:
values = ["42", "hello", "100"]Expected output:
42
Not a number
100Summary: Python Type Conversion
| Here's everything you learned about type conversion: | ||
|---|---|---|
| --- | --- | --- |
int() | Converts to integer (truncates floats) | int("42") → 42 |
float() | Converts to float | float("3.14") → 3.14 |
str() | Converts to string | str(42) → "42" |
bool() | Converts to boolean | bool(0) → False |
Key rules to remember:
bool → int → float)round() for roundingfloat() first: int(float("3.14"))What's Next?
Now that you can convert between data types, you have an essential skill for processing user input and building real programs. In the next tutorial, you'll learn how to write clean, readable Python code that other developers (and future you) will thank you for.