Skip to main content
Editor

Python Type Conversion: How to Convert Between Data Types

Beginner20 min5 exercises85 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/5 exercises

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.

Implicit vs explicit conversion
# Implicit conversion - Python does it automatically
result = 5 + 2.0
print(result) # 7.0
print(type(result)) # <class 'float'>
# Explicit conversion - you do it with a function
age_text = "25"
age = int(age_text)
print(age + 5) # 30
Output
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.

Implicit conversion examples
# int + float → float (automatic)
print(5 + 2.0) # 7.0 (not 7)
print(10 * 1.5) # 15.0
print(8 - 3.0) # 5.0
# bool + int → int (True = 1, False = 0)
print(True + 5) # 6
print(False + 10) # 10
# bool + float → float
print(True + 2.5) # 3.5
Output
7.0
15.0
5.0
6
10
3.5
Python refuses to guess with strings
# This works - both are numbers
print(5 + 2.0) # 7.0
# This CRASHES - string + int is not allowed
try:
print("5" + 3)
except TypeError as e:
print(f"Error: {e}")
Output
7.0
Error: can only concatenate str (not "int") to str

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.

Float to int: truncation, not rounding
# int() truncates - it does NOT round
print(int(3.9)) # 3 - not 4!
print(int(3.1)) # 3
print(int(-2.7)) # -2 - truncates toward zero
print(int(99.999)) # 99
# If you want rounding, use round() instead
print(round(3.9)) # 4
print(round(3.1)) # 3
Output
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.

String and bool to int
# Valid string-to-int conversions
print(int("42")) # 42
print(int("-7")) # -7
print(int(" 100 ")) # 100 - spaces are stripped
# Booleans to int
print(int(True)) # 1
print(int(False)) # 0
Output
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.

Converting to float
# int to float
print(float(42)) # 42.0
print(float(-7)) # -7.0
print(float(0)) # 0.0
# string to float
print(float("3.14")) # 3.14
print(float("7")) # 7.0
print(float("-2.5")) # -2.5
# bool to float
print(float(True)) # 1.0
print(float(False)) # 0.0
Output
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.

Converting to string
# Numbers to string
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(str(-7)) # "-7"
# Booleans to string
print(str(True)) # "True"
print(str(False)) # "False"
# None to string
print(str(None)) # "None"
# Now you can concatenate
age = 25
print("I am " + str(age) + " years old") # I am 25 years old
Output
42
3.14
-7
True
False
None
I am 25 years old
Using str() and concatenation
name = "Alice"
age = 25
print("Name: " + name + ", Age: " + str(age))
Using f-strings (cleaner)
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.

Truthy and falsy conversions
# Falsy values - these all become False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool("")) # False - empty string
print(bool(None)) # False
print("---")
# Truthy values - these all become True
print(bool(1)) # True
print(bool(-5)) # True - any non-zero number
print(bool(3.14)) # True
print(bool("hello")) # True - any non-empty string
print(bool(" ")) # True - a space is still a character!
Output
False
False
False
False
---
True
True
True
True
True
Tricky bool() conversions
# Tricky cases - don't get fooled!
print(bool("0")) # True - non-empty string
print(bool("False")) # True - non-empty string
print(bool("None")) # True - non-empty string
print(bool(" ")) # True - space is a character
# Only the ACTUAL empty string is falsy
print(bool("")) # False
Output
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."

Common ValueError examples
# These conversions CRASH with ValueError
# Can't convert words to numbers
try:
print(int("hello"))
except ValueError as e:
print(f"Error 1: {e}")
# int() can't handle decimal strings
try:
print(int("3.14"))
except ValueError as e:
print(f"Error 2: {e}")
# float() can't handle words either
try:
print(float("abc"))
except ValueError as e:
print(f"Error 3: {e}")
Output
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:

ConversionExampleResult
int("42")String of digits42
int("3.14")String with decimalValueError
int("hello")Non-numeric stringValueError
float("3.14")String with decimal3.14
float("abc")Non-numeric stringValueError
int(float("3.14"))Two-step conversion3

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.

Checking with .isdigit() before converting
# .isdigit() checks if a string contains only digits
print("42".isdigit()) # True
print("3.14".isdigit()) # False - has a dot
print("-7".isdigit()) # False - has a minus sign
print("hello".isdigit()) # False
print("".isdigit()) # False - empty string
# Check before converting
user_input = "42"
if user_input.isdigit():
number = int(user_input)
print(f"Converted: {number}")
else:
print(f"Cannot convert: {user_input}")
Output
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.

Safe conversion with try/except
# try/except - the safest approach
def safe_int(value):
try:
return int(value)
except ValueError:
return None
# Works with valid input
print(safe_int("42")) # 42
print(safe_int("100")) # 100
# Returns None for bad input instead of crashing
print(safe_int("hello")) # None
print(safe_int("3.14")) # None
print(safe_int("")) # None
Output
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.

Exercise 1: String to Int and Multiply
Write Code

You have a string variable text containing "42". Convert it to an integer and multiply by 2. Print the result.

Expected output:

84
text = "42"
# Convert text to an integer and multiply by 2
# Print the result
Exercise 2: Float to Int: What Gets Lost?
Write Code

You 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.99

Hint: calculate what was lost by subtracting. Use round() on the lost amount to avoid floating-point weirdness.

price = 9.99
# Convert to int
# Calculate what was lost
# Print all three values
Exercise 3: Predict the Output: Type Conversions
Predict Output

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.

print(int(3.9)) # Your prediction:
print(float("7")) # Your prediction:
print(str(True)) # Your prediction:
print(bool(0)) # Your prediction:
Exercise 4: Fix the Bug: String and Int Concatenation
Fix the Bug

This code tries to build a message, but it crashes with a TypeError. Fix it so it prints:

You have 3 new messages

You can fix it any way you like (str(), f-strings, etc.).

count = 3
message = "You have " + count + " new messages"
print(message)
Exercise 5: Convert Only the Numbers
Write Code

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
100
values = ["42", "hello", "100"]
# Loop through values
# If the value is a digit, convert and print the integer
# Otherwise print "Not a number"

Summary: Python Type Conversion

Here's everything you learned about type conversion:

FunctionWhat it doesExample
int()Converts to integer (truncates floats)int("42") → 42
float()Converts to floatfloat("3.14") → 3.14
str()Converts to stringstr(42) → "42"
bool()Converts to booleanbool(0) → False

Key rules to remember:

  • Implicit conversion only happens between number types (bool → int → float)
  • int() truncates - it does not round. Use round() for rounding
  • int("3.14") crashes - go through float() first: int(float("3.14"))
  • Empty and zero values are falsy, everything else is truthy
  • Use try/except to convert input safely; .isdigit() is a quick first check for plain whole numbers
  • 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.

    Harder problems

    More problems on this topic: Python Basics

    Related Tutorials

    Was this tutorial helpful?