Python

Python Type Conversion

In Python, different values have different data types.

For example:

name = "Raj"       # string
age = 25           # integer
height = 5.8       # float
active = True      # boolean

Sometimes we need to convert a value from one data type to another.

This process is called Type Conversion or Type Casting.

For example:

age = "25"

age = int(age)

print(age)
print(type(age))

Output:

25
<class 'int'>

The string "25" has been converted into the integer 25.

1. What is Type Conversion?

Type conversion is the process of changing a value from one data type into another data type.

Common conversions include:

str → int
str → float
int → float
float → int
int → str
float → str
int → bool
list → tuple
tuple → list
list → set
set → list

Python provides built-in functions to perform these conversions.

Some of the most commonly used functions are:

int()
float()
str()
bool()
list()
tuple()
set()
dict()

2. Why Do We Need Type Conversion?

One common situation is receiving information from a user.

Consider:

age = input("Enter your age: ")

print(type(age))

If the user enters:

25

Python receives it as:

<class 'str'>

Even though the user entered a number, input() returns a string.

If we want to perform mathematical calculations, we need to convert it.

age = int(input("Enter your age: "))

print(age + 5)

If the user enters:

25

Output:

30

3. int() - Convert to Integer

The int() function converts a compatible value into an integer.

Example:

x = "25"

y = int(x)

print(y)
print(type(y))

Output:

25
<class 'int'>

4. String to Integer

age = "25"

age = int(age)

print(age + 5)

Output:

30

Before conversion:

"25"

After conversion:

25

The first is a string and the second is an integer.

5. Float to Integer

A floating-point number can also be converted to an integer.

price = 99.99

price = int(price)

print(price)

Output:

99

Important

int() does not round the number to the nearest integer.

It removes the fractional part.

For example:

print(int(9.8))
print(int(9.2))
print(int(-9.8))

Output:

9
9
-9

For negative numbers, this moves toward zero.

6. Integer to Integer

If the value is already an integer:

x = 50

y = int(x)

print(y)

The value remains an integer.

7. String Containing a Decimal

This will cause an error:

price = "99.99"

price = int(price)

Why?

Because "99.99" is not a valid integer representation.

Instead:

price = "99.99"

price = float(price)

print(price)

Output:

99.99

8. float() — Convert to Floating-Point Number

The float() function converts a compatible value into a floating-point number.

Example:

x = "25.5"

y = float(x)

print(y)
print(type(y))

Output:

25.5
<class 'float'>

9. Integer to Float

x = 25

y = float(x)

print(y)
print(type(y))

Output:

25.0
<class 'float'>

Python adds .0 because the result is now a floating-point value.

10. String to Float

price = "1500.75"

price = float(price)

print(price)

Output:

1500.75

This is particularly useful when working with prices, measurements, percentages, and calculations.

11. Float to Float

x = 10.5

y = float(x)

print(y)

The value remains a float.

12. str() - Convert to String

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

Example:

age = 25

age_text = str(age)

print(age_text)
print(type(age_text))

Output:

25
<class 'str'>

13. Why Convert to String?

Suppose:

age = 25

message = "My age is " + age

This produces an error because Python cannot directly concatenate a string and an integer using +.

Instead:

age = 25

message = "My age is " + str(age)

print(message)

Output:

My age is 25

14. Combining Different Types

You can also use str() when constructing text.

name = "Raj"
age = 25

print("My name is " + name + " and my age is " + str(age))

Output:

My name is Raj and my age is 25

Later, we will learn cleaner approaches using f-strings.

15. bool() - Convert to Boolean

The bool() function converts a value into either:

True

or:

False

Example:

x = 10

print(bool(x))

Output:

True

16. Boolean Conversion of Numbers

Generally:

0 → False
non-zero → True

Examples:

print(bool(0))
print(bool(1))
print(bool(10))
print(bool(-5))

Output:

False
True
True
True

17. Boolean Conversion of Strings

An important rule:

An empty string is False; a non-empty string is True.

print(bool(""))
print(bool("Hello"))
print(bool("0"))
print(bool("False"))

Output:

False
True
True
True

Notice:

bool("False")

is:

True

because "False" is a non-empty string.

Python does not interpret the text "False" as the Boolean value False.

18. Boolean Conversion of Lists

An empty collection is generally False.

print(bool([]))
print(bool([1, 2, 3]))

Output:

False
True

Similarly:

print(bool(()))
print(bool((1, 2)))

Output:

False
True

And:

print(bool(set()))
print(bool({1, 2}))

Output:

False
True

19. The Main False Values

Students should remember these common cases:

bool(0)
bool(0.0)
bool("")
bool([])
bool(())
bool(set())
bool({})
bool(None)

All produce:

False

Most other values are considered truthy.

This concept becomes extremely important when we learn if statements.

20. Converting a List to a Tuple

Use:

tuple()

Example:

fruits = ["apple", "mango", "banana"]

fruits_tuple = tuple(fruits)

print(fruits_tuple)
print(type(fruits_tuple))

Output:

('apple', 'mango', 'banana')
<class 'tuple'>

21. Converting a Tuple to a List

Use:

list()

Example:

fruits = ("apple", "mango", "banana")

fruits_list = list(fruits)

print(fruits_list)
print(type(fruits_list))

Output:

['apple', 'mango', 'banana']
<class 'list'>

This is useful when you need to modify a tuple's contents.

22. Converting a List to a Set

Use:

set()

Example:

numbers = [1, 2, 2, 3, 4, 4, 5]

unique_numbers = set(numbers)

print(unique_numbers)

The duplicate values are removed.

Possible output:

{1, 2, 3, 4, 5}

Important

Sets are unordered collections, so you should not depend on their displayed order.

23. Converting a Set to a List

numbers = {10, 20, 30}

numbers_list = list(numbers)

print(numbers_list)

The result is a list.

Remember that the ordering of a set should not be relied upon when converting it to another collection.

24. Converting a String to a List

Using:

list()

on a string creates a list containing its individual characters.

word = "Python"

letters = list(word)

print(letters)

Output:

['P', 'y', 't', 'h', 'o', 'n']

This is different from splitting a sentence into words.

For that, we use:

sentence = "Python is easy"

words = sentence.split()

print(words)

Output:

['Python', 'is', 'easy']

25. Converting a String to a Set

word = "banana"

letters = set(word)

print(letters)

The set contains unique characters.

For example, it may contain:

{'b', 'a', 'n'}

The order can vary because sets are unordered.

26. Converting a List of Pairs to a Dictionary

A dictionary can be created from an iterable containing key-value pairs.

Example:

data = [
    ("name", "Raj"),
    ("age", 25),
    ("city", "Kathmandu")
]

student = dict(data)

print(student)

Output:

{'name': 'Raj', 'age': 25, 'city': 'Kathmandu'}

This is a useful conversion when working with structured data.

27. Dictionary Keys and Values

We can convert dictionary views into lists or other collections.

student = {
    "name": "Raj",
    "age": 25,
    "city": "Kathmandu"
}

keys = list(student.keys())
values = list(student.values())

print(keys)
print(values)

Output:

['name', 'age', 'city']
['Raj', 25, 'Kathmandu']

28. Converting Dictionary Items

student = {
    "name": "Raj",
    "age": 25
}

items = list(student.items())

print(items)

Output:

[('name', 'Raj'), ('age', 25)]

Each item becomes a tuple containing:

(key, value)

29. Converting Between Numeric Types

A common conversion flow is:

string
   ↓
float
   ↓
int

Example:

price = "99.99"

price = float(price)
price = int(price)

print(price)

Output:

99

The original string was first converted into a float and then into an integer.

30. Type Conversion vs Type Checking

These are different operations.

Type checking

We use:

type()

Example:

x = "25"

print(type(x))

Type conversion

We use:

int()

Example:

x = "25"

x = int(x)

print(type(x))

So:

type() → tells us what type something is

int(), float(), str(), etc. → convert something to another type

31. Explicit Type Conversion

When the programmer manually converts a value, it is called explicit type conversion.

Example:

age = "25"

age = int(age)

We explicitly told Python:

Convert this value to an integer.

32. Implicit Type Conversion

Python can sometimes automatically convert one numeric type to another during an operation.

For example:

x = 10
y = 2.5

result = x + y

print(result)
print(type(result))

Output:

12.5
<class 'float'>

Python automatically promotes the integer to a compatible numeric type for the calculation.

This is called implicit type conversion.

33. Explicit vs Implicit Conversion

ExplicitImplicit
Programmer performs conversionPython performs conversion
Uses functions such as int()Happens automatically in certain operations
int("25")10 + 2.5
Conversion is directly visibleConversion happens behind the scenes

34. Invalid Conversions

Not every value can be converted successfully.

For example:

x = "hello"

print(int(x))

This causes a:

ValueError

because "hello" does not represent an integer.

Another example:

x = "Python"

print(float(x))

This also produces a ValueError.

The value must have a compatible representation.

35. Converting an Empty String

This also fails:

x = ""

print(int(x))

An empty string does not represent an integer.

But:

print(bool(""))

works and produces:

False

Different conversion functions have different rules.

36. Converting None

Be careful with None.

For example:

x = None

print(str(x))

Output:

None

But:

print(int(None))

will raise a TypeError.

Likewise:

print(float(None))

is invalid.

However:

print(bool(None))

produces:

False

37. Converting User Input

This is one of the most important practical uses of type conversion.

Without conversion

age = input("Enter your age: ")

print(age + "5")

If the user enters:

25

the result is:

255

because both values are strings.

With conversion

age = int(input("Enter your age: "))

print(age + 5)

Now the result is:

30

38. Multiple User Inputs

name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

print("Name:", name)
print("Age:", age)
print("Height:", height)

This is a very common pattern in Python programs.

39. Practical Example — Shopping

price = float(input("Enter product price: "))
quantity = int(input("Enter quantity: "))

total = price * quantity

print("Total:", total)

Example:

Enter product price: 250.50
Enter quantity: 3

Output:

Total: 751.5

40. Practical Example - Student Marks

name = input("Enter student name: ")

python_marks = float(input("Enter Python marks: "))
database_marks = float(input("Enter Database marks: "))
web_marks = float(input("Enter Web marks: "))

total = python_marks + database_marks + web_marks
average = total / 3

print("Student:", name)
print("Total:", total)
print("Average:", average)

Here:

  • input() receives strings.
  • float() converts marks to numbers.
  • Arithmetic is then performed on the numeric values.

41. Practical Example - Collection Conversion

fruits = ["apple", "mango", "apple", "banana"]

print("Original:", fruits)

unique_fruits = set(fruits)

print("Unique:", unique_fruits)

fruit_tuple = tuple(unique_fruits)

print("Tuple:", fruit_tuple)

This demonstrates:

List
 ↓
Set
 ↓
Tuple

42. Important Difference: int() vs round()

Students often confuse these two.

x = 9.7

print(int(x))
print(round(x))

Output:

9
10

int() removes the fractional portion.

round() performs rounding according to Python's rounding rules.

So:

int(9.7)   → 9
round(9.7) → 10

43. Important Difference: str() vs repr()

For beginner-level programming, str() is normally used when we want a readable text representation.

Example:

age = 25

print(str(age))

Output:

25

repr() has a different purpose and is more useful when debugging or representing objects precisely.

We can introduce repr() later when discussing objects and debugging.

44. Conversion Cheat Sheet

FunctionPurposeExampleResult
int()Convert to integerint("25")25
float()Convert to floatfloat("25.5")25.5
str()Convert to stringstr(25)"25"
bool()Convert to Booleanbool(1)True
list()Convert to listlist("abc")['a','b','c']
tuple()Convert to tupletuple([1,2])(1,2)
set()Convert to setset([1,1,2]){1,2}
dict()Create dictionarydict([("a",1)]){'a':1}

45. Copy Code

# ==========================================
# Python Type Conversion
# ==========================================

# String to integer

age = "25"
age = int(age)

print(age)
print(type(age))


# String to float

price = "99.50"
price = float(price)

print(price)
print(type(price))


# Integer to float

number = 10
number = float(number)

print(number)
print(type(number))


# Float to integer

number = 10.75
number = int(number)

print(number)
print(type(number))


# Integer to string

age = 25
age_text = str(age)

print(age_text)
print(type(age_text))


# Number to boolean

print(bool(0))
print(bool(1))
print(bool(100))


# String to boolean

print(bool(""))
print(bool("Python"))
print(bool("False"))


# List to tuple

fruits = ["apple", "mango", "banana"]

fruits_tuple = tuple(fruits)

print(fruits_tuple)


# Tuple to list

numbers = (10, 20, 30)

numbers_list = list(numbers)

print(numbers_list)


# List to set

values = [1, 2, 2, 3, 4, 4, 5]

unique_values = set(values)

print(unique_values)


# Set to list

numbers = {10, 20, 30}

numbers_list = list(numbers)

print(numbers_list)


# String to list

word = "Python"

letters = list(word)

print(letters)


# String to set

word = "banana"

unique_letters = set(word)

print(unique_letters)


# List of pairs to dictionary

data = [
    ("name", "Raj"),
    ("age", 25),
    ("city", "Kathmandu")
]

student = dict(data)

print(student)


# Dictionary keys and values

keys = list(student.keys())
values = list(student.values())

print(keys)
print(values)


# User input conversion

name = input("Enter your name: ")
age = int(input("Enter your age: "))

print("Name:", name)
print("Age:", age)


# Calculation using converted values

price = float(input("Enter product price: "))
quantity = int(input("Enter quantity: "))

total = price * quantity

print("Total:", total)

46. Practice Exercise 1 :  Age Calculator

Ask the user for their birth year:

birth_year = input("Enter your birth year: ")

Convert the input to an integer and calculate their approximate age using the current year.

Example:

Enter your birth year: 2000

Your approximate age is: 26

47. Practice Exercise 2 : Shopping Calculator

Ask the user for:

  • Product name
  • Price
  • Quantity

Convert the price and quantity into appropriate numeric types.

Calculate the total.

Example:

Product: Mouse
Price: 800
Quantity: 3

Total: 2400

48. Practice Exercise 3 : Marks Calculator

Ask the user for marks in:

  • Python
  • Database
  • Web Development

Convert the entered marks into numbers.

Calculate:

Total
Average

49. Practice Exercise 4 : Remove Duplicates

Given:

numbers = [10, 20, 20, 30, 40, 40, 50]

Convert the list into a set to remove duplicate values.

Then convert it back into a list.

Expected concept:

List
 ↓
Set
 ↓
List

50. Practice Exercise 5 : String Conversion

Given:

name = "Raj"
age = 25
course = "Python"

Create one sentence using string conversion:

My name is Raj, I am 25 years old, and I am learning Python.

51. Challenge : Student Registration

Create a program that asks for:

Student Name
Age
Course Fee
Number of Courses

Remember:

  • Name → str
  • Age → int
  • Course Fee → float
  • Number of Courses → int

Then display the information and its data types.

For example:

Student: Raj
Age: 25
Course Fee: 15000.0
Courses: 2

 

 

Interactive Sandbox
Python