Python Type Conversion: How to Convert Between Data Types
Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย
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.
7.0 <class 'float'> 30
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 for everyday numbers: a float holds every integer up to about 9 quadrillion exactly.
7.0 15.0 5.0 6 10 3.5
7.0 Error: can only concatenate str (not "int") to str
How to Convert to Integer with int()
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.
3 3 -2 99 4 3
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.
42 -7 100 1 0
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 everyday integer to a float loses nothing: the number gets a .0 added to the end, like a price of $5 written as $5.00. Only an integer past the limit above (2 ** 53) can lose its last digits.
42.0 -7.0 0.0 3.14 7.0 -2.5 1.0 0.0
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.
42 3.14 -7 True False None I am 25 years old
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.
False False False False --- True True True True True
True True True True False
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."
Error 1: invalid literal for int() with base 10: 'hello' Error 2: invalid literal for int() with base 10: '3.14' Error 3: could not convert string to float: 'abc'
Here's a quick reference of what works and what doesn't:
| Conversion | Example | Result |
|---|---|---|
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. You can check before converting with methods like .isdigit(), or you can try and catch the error with try/except, the safer of the two.
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 a string before converting it to an integer.
True False False False False Converted: 42
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.
42 100 None None None
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 only the ones made of digits to integers. 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:
| Function | What it does | Example |
|---|---|---|
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)int() truncates - it does not round. Use round() for roundingint("3.14") crashes - go through float() first: int(float("3.14"))try/except to convert input safely; .isdigit() is a quick first check for plain whole numbersWhat'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.