×

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 complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Python String Variable

Python programming language: 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...

4 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.