Casting
Casting, also known as type conversion, is a process that converts a variable’s data type into another data type. These conversions can be implicit (automatically interpreted) or explicit (using built-in functions).
Implicit Type Conversion
The Python interpreter automatically performs type conversion on some operations without any user involvement.
Python avoids data loss by converting lower data types to higher data types. For example, an integer, 7, is converted to a float when added with another float, 2.2:
y = 7 + 2.2# Python automatically type casts y into floatprint(y)# Output: 9.2print(type(y))# Output: <class 'float'>
Since the expression above represents the sum of two float
values, the data type of y
is also a float
.
Explicit Type Conversion
Explicit type casting involves Python’s predefined functions that act as a constructor of another data type:
- The
str()
function takes an integer or float as an argument and converts it to a string. - The
int()
function takes a string or float as an argument converts it to an integer. - The
float()
function takes an integer or string as an argument and converts it to a float.
Operations on Different Types of Data
When operating on data, it is important to be mindful of the data types associated with it. The following code is a flawed attempt to print the square of a number specified by the user. When run, a TypeError
will be thrown:
The input()
function takes input from the user and stores it in a variable as a string. However, the **
operator takes two numbers and returns the first number to the power of the second. In order to make the code work, the input variable must be cast to a number type.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours