×

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

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Poolmanager in Python

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.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

How to create a dictionary in Python?

How to create a dictionary in python Dictionary is a data structure in Python that represents our data in the form of keys and values. Each value in a dictionary can be...

5 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

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