Type Conversion & Type Casting in Python Explained with Examples

Type Conversion & Type Casting in Python Explained with Examples

Last updated:
19th Feb, 2020
Views
7 Mins
View All

Python has many data types, and as a programmer, you should know how to convert one data type of Python into another. Python has many built-in functions for this task. And in this simple guide, we’ll be taking a look at them to help you understand type conversions better.

After you’re through with this guide, you would know how to convert strings into integers and vice versa. So without further ado, let’s get started.

Data Types in Python

Before we begin our discussion on type conversion in Python, let’s take a brief look at all data types present in this language:

Integers

Integer values can be as long as you want. Like in mathematics, integers in Python are digits too. But you can’t have indefinitely long integers unless you have a supercomputer. Python treats any number without a prefix as an integer. These numbers include decimal digits too.

Floating Point Numbers

Floats in Python are numbers that are written with a decimal point for separating the fractional digits and the integer. Some examples of floating-point numbers are 4.3, 9.18, etc. You can add ‘e’ for the scientific notation in Python as well.

Complex Numbers

Complex numbers in Python follow this format: (the real part + the imaginary part). Some examples of complex numbers are (3+2i), (8-2x), etc.

Strings

Strings can be any particular set of characters in Python. They are referred to as str. You can write them by using quotation marks. You can use single quotes as well as double quotes for writing strings in Python. Strings can be any characters placed in quotation marks such as ’91’, “hello”, etc.

Just like integers, there is no limit to character length in strings. Strings are of various types, such as triple-quoted strings, raw strings, and many others. However, if we would start discussing strings and their kinds, this article will go too long.

Boolean Data Type

The final data type we have left to discuss is the Boolean data type. Boolean data can have one of two values, which are true and false. Boolean values are quite essential in Python for many reasons. You can use Boolean values to determine the truthiness of objects and values.

Read: Python Developer Salary in India 2020

As you’ll learn more about logical operators in Python, you will have to deal with Boolean objects and values.

So these were all data types present in Python. Learn more about the data types in Python. Apart from these data types, Python also has many built-in functions, which help it in performing a variety of tasks. We’ll need to use a few built-in functions to implement type conversion as well. Checkout our data science programs to learn about various types of conversions.

Now that we’ve discussed data types, we can move onto type conversion.

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

Different Kinds of Type Conversions in Python

There are two kinds of type conversions in Python. They are the following:

Implicit

In this case, Python converts a data type into another type automatically. You, the user, don’t have to get involved in this process. Here is an example of implicit conversion of integer to float in Python:

num_int = 18

num_flo = 1.8

num_new = num_int + num_flo

print(“datatype of num_int:”,type(num_int))

print(“datatype of num_flo:”,type(num_flo))

print(“Value of num_new:”,num_new)

print(“datatype of num_new:”,type(num_new))

The output of the above code would be the following:

datatype of num_int: <class ‘int’>

datatype of num_flo: <class ‘float’>

Value of num_new: 19.8

datatype of num_new: <class ‘float’>

As you can see, we only had to add num_flo and num_int along with num_new to get the desired output. We converted the integer 18 into a float 19.8 through a few lines of code. The vital thing to note here is that Python turned the integer into float automatically.

Explore our Popular Data Science Courses

 Executive Post Graduate Programme in Data Science from IIITB Professional Certificate Program in Data Science for Business Decision Making Master of Science in Data Science from University of Arizona Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland Data Science Courses

Explicit

In the case of explicit type conversion, we use functions for converting purposes. Remember the built-in functions we mentioned before? They will come in handy in this section. Another name for explicit type conversions is typecasting. It has this name because you, the user, cast the data type of the concerned object.

There are some type conversion functions you should be familiar with to perform typecasting in Python. Int(a,base) is a popular function as it can convert any data type into an integer. float() can turn any data type into a floating-point number. oct() converts integers to octal strings, and hex() converts integers to hexadecimal strings.

Here is an example of type conversion using oct():

c = oct(80)

print (“Output : “,end=””)

print (c)

And the output would be:

Output : 0o120

When working with these functions, remember that the syntax for such conversion should be:

(desired_datatype)(expression)

There are many kinds of type conversions you can perform in Python. However, there are two kinds of them, which you’ll be performing the most. Converting strings into integers and vice versa can be a great starting point. So let’s discuss each of those type conversions separately for a better understanding of this topic:

Converting String to int Python

You can convert a string to int Python through the int() function. It gives you a decimal integer with just a click. It assumes that the expression you’ve entered is a decimal integer, but if it’s not, it will return a ValueError. And we don’t want that. You can mention the number system you require by giving the value a base to avoid this problem.

So, if you’re converting a string to int in Python you can do this:

int(“5”)

Or, you can add a base for different kinds of strings:

int(“5” , base=10)

Now let’s discuss the reverse of this conversion, i.e. when you need to convert an integer into a string.

Converting int to String Python

You can use the str() function for converting integers into strings. Just follow the syntax we mentioned before:

str(5)

Strings can convert integers into decimal expressions if you use a binary literal. However, just like with the int function, if you require, you can add more information for different conversions. You can get octal, binary, and even hexadecimal results with this function.

After a little practice, you can perform more complex tasks with type conversion as well. Here’s an example of adding a string with an integer through typecasting:

num_int = 256

num_str = “64”

print(“Data type of num_int:”,type(num_int))

print(“Data type of num_str before Type Casting:”,type(num_str))

num_str = int(num_str)

print(“Data type of num_str after Type Casting:”,type(num_str))

num_sum = num_int + num_str

print(“Sum of num_int and num_str:”,num_sum)

print(“Data type of the sum:”,type(num_sum))

The output of the above code would be this:

Data type of num_int: <class ‘int’>

Data type of num_str before Type Casting: <class ‘str’>

Data type of num_str after Type Casting: <class ‘int’>

Sum of num_int and num_str: 320

Data type of the sum: <class ‘int’>

As you can see, it’s a lot of fun. Feel free to experiment with type conversions and expand your knowledge base.

Top Data Science Skills to Learn

 Top Data Science Skills to Learn 1 Data Analysis Course Inferential Statistics Courses 2 Hypothesis Testing Programs Logistic Regression Courses 3 Linear Regression Courses Linear Algebra for Analysis

Conclusion

We hope you learned a lot from this article. Performing type conversions is one of the many things you can do with Python’s functions.

If you are reading this article, most likely you have ambitions towards becoming a Python developer. If you’re interested to learn python & want to get your hands dirty on various tools and libraries, check out IIIT-B’s PG Diploma in Data Science.

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select
Select Area of interest
Select Work Experience
By clicking 'Submit' you Agree to
UpGrad's Terms & Conditions

Frequently Asked Questions (FAQs)

1In coding, how are explicit conversions different from implicit conversions?

An implicit type conversion is a type conversion that is defined by the user and compels an expression to be of a certain type. When several data types are combined together in an expression, the compiler performs an implicit type conversion. Explicit conversion, also known as casting, is when we explicitly convert from one data type to another by executing the appropriate function for the data type we wish to convert to. Without the assistance of the programmer, an implicit type conversion is accomplished.

2How is type casting different from type conversion?

The destination data type must be smaller than the source data type when type casting one data type to another. However, the source data needs to be smaller than the destination data type when converting one data type to another. A programmer must manually type cast one kind of data into another type. Converting one data type to another does not involve any programmer intervention because the compiler automatically compiles it during program execution. There is a chance that data or information will be lost during type casting. When converting a small data type to a large data type, data is unlikely to be lost.

3Which is more efficient in Python- tuples or lists?

A tuple is a comma-separated collection of Python objects and because of its static nature, the tuple is quicker than the list. Tuples are also more efficient in terms of memory than lists. When it comes to time efficiency, tuples have a minor edge over lists, particularly when it comes to looking up to a value. If you have data that isn't supposed to be altered in the first place, a tuple data type should be preferred over a list. We may make a list of tuples, which means that the members of the tuple can be wrapped in a list and therefore follow the same characteristics as a Python list. Because Python Tuples take up less space, constructing a list of tuples is more practical.

Suggested Blogs

61616
In this article, you will learn about the Types of Trees in Data Structures with examples, Properties & Applications. In my journey with data stru

31 May 2024

40522
The communication network is expanding, and so the people are using the internet! Businesses are going digital for efficient management. The data gene

29 May 2024

54858
Data structures are the data structured in a way for efficient use by the users. As the computer program relies hugely on the data and also requires a

28 May 2024

318167
Summary: In this Article, you will learn about what are the 4 Types of Data in Statistics. Qualitative Data Type Nominal Ordinal Quantitative Data

28 May 2024

909073
Wondering what is the range of Python developer salary in India? Before going deep into that, do you know why Python is so popular now? Python has be

by Sriram

21 May 2024

89487
Data structures serve as the backbone of efficient data organization and management within computer systems. They play a pivotal role in computer algo

21 May 2024

23238
Summary: In this Article, you will learn about Data Analyst Salary in India in 2024. Data Science Job roles Average Salary per Annum Data Scient

20 May 2024

135967
Summary: In this Article, you will learn about python free online course with certification. Programming with Python: Introduction for Beginners Le

20 May 2024

249656
In the world of computer science, understanding data structures is essential, especially for beginners. These structures serve as the foundation for

20 May 2024

Schedule 1:1 free counsellingTalk to Career Expert