×

Type casting in Python

Introduction

Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This can be performed with the use of construction functions such as int(). string(), float(), etc. 

The execution of the process in Type Casting can be performed by using two different techniques available in Type Casting.

Two types of Type Casting techniques are:

1. Implicit Type Casting.
2. Explicit Type Casting.

1. Implicit Type Casting

In Implicit Type Casting, users don’t have to involve in this process. The Python automatically converts one data type into another data type. It does not require the  involvement of the user. The conversion of lower data types is supported by Python such as integer to float conversion avoids loss of data. This Type of Casting is also known as Upcasting.

2. Explicit Type casting

The data type of an object is converted to the needed data type by the user or programmer in Exliplicit Type Casting.

To perform Explicit Type Casting, the predefined functions are used such as int(), float(), str(), bool(), etc in Python. In this Type Castin, the users have to involve in this process. It requires the involvement of users for performing Type Casting.

Syntax:

(Required datatype) (Expression)

Examples of Implicit Type Casting in Python.

Example 1 : Program to demonstrate Implicit Type conversion/casting.

# Python program for demonstrating implicit type casting

# program for adding two numbers

x = 26

y = 20

print("Type of first number(x) :", x, type(x))

print("Type of second number(y) :", y, type(y))

z = x + y

print("The resulting variable type is(z) :",

z, type(z))   

Output:

Type of first number(x) : 26 <class 'int'>

Type of second number(y) : 20 <class 'int'>

The resulting variable type is(z) : 46 <class 'int'>

In the above example. the adding() function is defined. first input number type, second input number type and the type of result is printed.

Example 2:

# Python program for demonstrating implicit type casting

# x will automatically converts into int

x = 8

print(type(x))

# y will automatically converts into float

y = 6.0

print(type(y))

# z will automatically convert into float

# as it is a float addition

z = x + y

print(z)

print(type(z))

# m will automatically converts into float

# as it is a float multiplication

m = x * y

print(m)

print(type(m))

Output:

<class 'int'>

<class 'float'>

14.0

<class 'float'>

48.0

<class 'float'>

Examples of Explicit Type Casting in Python.

Example 1:

# Python program for demonstrating Explicit type casting

first_num = 298

second_num = "592"

# printing the data types

print("Data type of first_num :",type(first_num))

print("Data type of second_num before Type Casting:",type(second_num))

second_num = int(second_num)

print("Data type of second_num after Type Casting:",type(second_num))

sum =  first_num + second_num

# printing the resultant data type

print("Sum of first_num and second_num:", sum)

print("Data type of the sum:",type(sum))

Output:

Data type of first_num : <class 'int'>

Data type of second_num before Type Casting: <class 'str'>

Data type of second_num after Type Casting: <class 'int'>

Sum of first_num and second_num: 890

Data type of the sum: <class 'int'>

Now, we are using constructor functions like int(), float(), str() etc  for defining Explicit Type Casting

Example 2: Here, we are performing Explicit Type Casting by converting string, float, bool data type into integer data type with int() function.

# Python program for demonstrating

# Explicit type Casting

print("typecast to integer type")

print(int(15.9)) # float to int

print(int(True)) # bool to int

print(int(False)) # bool to int

print("321") # str to int

print('\n')

Output:

typecast to integer type

15

1

0

321

Example 3: Here, we are performing Explicit Type Casting by converting string, bool, int data type into float data type with float() function.

# Python program for demonstrating

# Explicit type Casting

print("converting to floating type")

print(float(19)) # int to float

print(float(True)) # bool to float

print(float(False)) # bool to float

print(float("456")) # string to float

print('\n')

Output:

converting to floating type

19.0

1.0

0.0

456.0

Example 4: Here, we are performing Explicit Type Casting by converting list, tuple, float, int data type into bool type using the bool() function.

# Python program for demonstrating

# Explicit type Casting

print("converting to boolean type")

print(bool(23)) # integer to bool

print(bool(1.1)) # float to bool

print(bool([4,5,6])) # list to bool

print(bool()) # tuple to bool

print('\n')

Output:

converting to boolean type

True

True

True

False

Example 5: Here, we are performing Explicit Type Casting by converting list, float, int data type into string type using str()function.

# Python program for demonstrating

# Explicit type Casting

print("converting to string type")

print(str(456)) # integer to string

print(str(15.12)) # float to string

print(str([20, 30, 40])) # list to strings

Output:

Converting to string type

456

15.12

[20, 30, 40]

Conclusion

In the above article, we have seen Type Casting in Python. Python offers two types of conversions Implicit Type and Explicit Type Casting/Conversions. You have learned the concept of both conversions in Python. Now, you can easily perform Type Casting operations in Python.


Related Topics

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

How to Plot Graphs Using Python?

In this article, we are going to learn about how to plot different types of graphs using Python. We are going to use different approaches for every type of graph....

3 minutes read.

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

AX Contour in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.