Python Type Conversion
Learn how to convert values from one Python data type
to another using built-in conversion functions such as
int(), float(),
str(), and bool().
What You'll Learn
- Understand implicit and explicit type conversion.
- Use Python's built-in conversion functions.
- Convert strings into numbers and numbers into strings.
- Understand how
input()interacts with conversion. - Recognize invalid conversions and
ValueError. - Avoid common type-conversion mistakes.
What Is Type Conversion?
Type conversion means changing a value from one data type into another data type.
For example, a number stored as text can be converted into an integer:
age = "25"
age = int(age)
print(age)
25
Before conversion, age was a string.
After conversion, it is an integer.
Type conversion allows different kinds of values to work together correctly in your programs.
Why Is Type Conversion Needed?
Python treats different data types differently. Sometimes a value arrives in a type that is not suitable for the operation you want to perform.
A very common example is user input.
age = input("Enter your age: ")
print(type(age))
Enter your age: 25 <class 'str'>
Even though the user typed 25, Python receives it as a string.
If we want to perform mathematical calculations, we usually need to convert it first.
age = int(input("Enter your age: "))
print(age + 1)
Enter your age: 25 26
Implicit Type Conversion
Implicit conversion happens automatically. Python converts a value when necessary without you explicitly calling a conversion function.
A common example occurs when an integer and a floating-point number are used together.
number = 10
decimal = 2.5
result = number + decimal
print(result)
print(type(result))
12.5 <class 'float'>
Python automatically promotes the integer value to a floating-point value for the calculation.
Implicit conversion is performed by Python automatically. You do not call a conversion function yourself.
Explicit Type Conversion
Explicit conversion is when you deliberately tell Python which type you want.
Python provides several built-in functions for this.
number = "50"
number = int(number)
print(number)
print(type(number))
50 <class 'int'>
Here, the programmer explicitly requested conversion
using int().
Converting Values with int()
The int() function converts a compatible value
into an integer.
String to Integer
age = int("25")
print(age)
print(type(age))
25 <class 'int'>
Float to Integer
number = int(3.9)
print(number)
3
Converting a float to an integer removes the decimal portion. It does not round the number.
For example, int(7.99) produces
7, not 8.
Converting Values with float()
The float() function converts a compatible
value into a floating-point number.
price = float("19.99")
print(price)
print(type(price))
19.99 <class 'float'>
Integers can also be converted into floating-point values.
number = float(10)
print(number)
10.0
Converting Values with str()
The str() function converts a value into
a string.
number = 100
text = str(number)
print(text)
print(type(text))
100 <class 'str'>
This is especially useful when combining numbers with text outside of formatted strings.
age = 25
message = "I am " + str(age) + " years old."
print(message)
I am 25 years old.
Converting Values with bool()
The bool() function converts a value into
either True or False.
print(bool(1))
print(bool(0))
print(bool("hello"))
print(bool(""))
True False True False
Common False Values
Several values are considered false-like in Python, including:
False00.0""— empty string[]— empty list()— empty tuple{}— empty dictionaryNone
Most non-empty collections and non-zero numbers evaluate
to True.
Converting Values with list()
The list() function can convert an iterable
into a list.
String to List
letters = list("Python")
print(letters)
['P', 'y', 't', 'h', 'o', 'n']
Tuple to List
numbers = (10, 20, 30)
result = list(numbers)
print(result)
[10, 20, 30]
Converting Values with tuple()
The tuple() function converts an iterable
into a tuple.
numbers = [1, 2, 3, 4]
result = tuple(numbers)
print(result)
(1, 2, 3, 4)
Remember that lists are mutable while tuples are immutable.
Converting Values with set()
The set() function converts an iterable
into a set.
numbers = [1, 1, 2, 2, 3, 3]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3}
Converting a list to a set is a common way to remove duplicate values.
Converting Values with dict()
The dict() function can create a dictionary
from suitable key-value pairs.
pairs = [
("name", "Ali"),
("age", 25)
]
person = dict(pairs)
print(person)
{'name': 'Ali', 'age': 25}
Each pair contains a key followed by its corresponding value.
The input must provide suitable key-value pairs.
A simple list such as [1, 2, 3]
cannot be directly converted into a dictionary.
User Input and Type Conversion
One of the most important real-world uses of type conversion is handling user input.
The input() function always returns a string.
Example: Adding Two Numbers
first = input("Enter first number: ")
second = input("Enter second number: ")
result = int(first) + int(second)
print(result)
Enter first number: 15 Enter second number: 25 40
A Cleaner Approach
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
print(first + second)
Converting the input immediately makes the variable ready for mathematical operations.
If the user is entering a whole number, consider
using int(input(...)). For decimal
values, use float(input(...)).
Conversion Errors
Not every value can be converted into every data type. When a conversion is invalid, Python raises an error.
Invalid Integer Conversion
number = int("hello")
ValueError: invalid literal for int()
Python cannot interpret the word "hello"
as an integer.
Invalid Float Conversion
price = float("Python")
This also produces a ValueError.
Users may enter unexpected values. Later in this
course, you will learn how to handle conversion
errors using try and
except.
Common Type Conversion Mistakes
Mistake 1: Adding Strings Instead of Numbers
first = "10"
second = "20"
print(first + second)
1020
Python concatenates the strings instead of performing arithmetic.
Correct version:
first = "10"
second = "20"
print(int(first) + int(second))
30
Mistake 2: Expecting int() to Round
print(int(8.9))
8
int() truncates the decimal portion.
It does not perform normal rounding.
Mistake 3: Forgetting That input() Returns a String
age = input("Age: ")
print(age + 5)
This causes a type error because Python cannot add an integer directly to a string.
Use:
age = int(input("Age: "))
print(age + 5)
Practice Exercises
Exercise 1
Convert the string "100" into an integer
and print its type.
Exercise 2
Convert 25 into a floating-point number.
Exercise 3
Convert the number 500 into a string and
print its type.
Exercise 4
Predict the output:
print(int(9.99))
print(float("20"))
print(bool(0))
print(bool("Python"))
Exercise 5
Ask the user for their birth year and calculate approximately how old they will be in the year 2030.
Mini Challenge
Simple Bill Calculator
Create a program that asks the user for:
- Product price
- Quantity
Convert both values into suitable numeric types and calculate the total bill.
For example, if the price is 250.50
and the quantity is 3, the program should
calculate:
250.50 × 3 = 751.50
Use float() for the price and
int() for the quantity.
Quick Knowledge Check
Test what you have learned in this lesson.
1. What does int("25") return?
2. What type does input() return?
3. What is int(5.9)?
4. What does str(100) produce?
5. What does bool(0) return?
6. What happens with int("hello")?
Lesson Summary
Type conversion allows Python programs to change values from one data type into another.
int() converts compatible values
to integers.
float() converts compatible values
to floating-point numbers.
str() converts values to strings.
bool() converts values to
True or False.
list(), tuple(), and
set() can convert suitable iterables.
input() always returns a string,
so conversion is often required.
ValueError.
Always know what type of data your program is working with. When necessary, convert the value before performing an operation.
Finished Lesson 08?
Mark this lesson as complete and continue learning how Python handles input and output.