PyLearn Learn Python Step by Step
PyLearn / Python Foundations / Type Conversion
Lesson 08 · Foundations Beginner

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().

25–35 minutes Python Foundations
0%

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.
01

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)
Output
25

Before conversion, age was a string. After conversion, it is an integer.

Key idea

Type conversion allows different kinds of values to work together correctly in your programs.

02

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))
Example Output
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)
Output
Enter your age: 25
26
03

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))
Output
12.5
<class 'float'>

Python automatically promotes the integer value to a floating-point value for the calculation.

Remember

Implicit conversion is performed by Python automatically. You do not call a conversion function yourself.

04

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))
Output
50
<class 'int'>

Here, the programmer explicitly requested conversion using int().

05

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))
Output
25
<class 'int'>

Float to Integer

number = int(3.9)

print(number)
Output
3
Important

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.

06

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))
Output
19.99
<class 'float'>

Integers can also be converted into floating-point values.

number = float(10)

print(number)
Output
10.0
07

Converting Values with str()

The str() function converts a value into a string.

number = 100

text = str(number)

print(text)
print(type(text))
Output
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)
Output
I am 25 years old.
08

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(""))
Output
True
False
True
False

Common False Values

Several values are considered false-like in Python, including:

  • False
  • 0
  • 0.0
  • "" — empty string
  • [] — empty list
  • () — empty tuple
  • {} — empty dictionary
  • None

Most non-empty collections and non-zero numbers evaluate to True.

09

Converting Values with list()

The list() function can convert an iterable into a list.

String to List

letters = list("Python")

print(letters)
Output
['P', 'y', 't', 'h', 'o', 'n']

Tuple to List

numbers = (10, 20, 30)

result = list(numbers)

print(result)
Output
[10, 20, 30]
10

Converting Values with tuple()

The tuple() function converts an iterable into a tuple.

numbers = [1, 2, 3, 4]

result = tuple(numbers)

print(result)
Output
(1, 2, 3, 4)

Remember that lists are mutable while tuples are immutable.

11

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)
Output
{1, 2, 3}
Useful technique

Converting a list to a set is a common way to remove duplicate values.

12

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)
Output
{'name': 'Ali', 'age': 25}

Each pair contains a key followed by its corresponding value.

Not every iterable can become a dictionary

The input must provide suitable key-value pairs. A simple list such as [1, 2, 3] cannot be directly converted into a dictionary.

13

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)
Example Output
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.

Practical rule

If the user is entering a whole number, consider using int(input(...)). For decimal values, use float(input(...)).

14

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")
Result
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.

Be careful with user input

Users may enter unexpected values. Later in this course, you will learn how to handle conversion errors using try and except.

15

Common Type Conversion Mistakes

Mistake 1: Adding Strings Instead of Numbers

first = "10"
second = "20"

print(first + second)
Output
1020

Python concatenates the strings instead of performing arithmetic.

Correct version:

first = "10"
second = "20"

print(int(first) + int(second))
Output
30

Mistake 2: Expecting int() to Round

print(int(8.9))
Output
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)
16

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.

17

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
Hint

Use float() for the price and int() for the quantity.

18

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")?

19

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.
Invalid conversions can raise ValueError.
Key takeaway

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.