Type Conversion in Python
Type Conversion in Python
Type conversion in Python refers to the process of converting one data type to another. Python provides two types of type conversion:
Implicit Type Conversion (also known as type coercion)
Explicit Type Conversion (also known as type casting)
Let’s explore both with examples.
1. Implicit Type Conversion (Type Coercion)
Python automatically converts one data type to another when required, without needing the programmer to specify the conversion. This typically happens when you perform operations involving different data types.
Example:
In the above example, the integer a
is automatically converted to a float when added to the float b
, resulting in a float output.
2. Explicit Type Conversion (Type Casting)
Explicit type conversion occurs when you manually convert one data type to another using Python’s built-in functions like int()
, float()
, str()
, etc.
Common Type Conversion Functions:
int()
: Converts a value to an integer.float()
: Converts a value to a float.str()
: Converts a value to a string.bool()
: Converts a value to a boolean (True or False).
Example 1: Converting String to Integer
In this example, the string "25"
is converted to the integer 25
.
Example 2: Converting Integer to Float
Here, the integer 10
is explicitly converted to a float 10.0
.
Example 3: Converting Float to Integer
In this case, the float 10.75
is converted to the integer 10
. Note that the decimal part is truncated (not rounded).
Example 4: Converting Integer to String
Here, the integer 50
is converted to the string "50"
.
Example 5: Converting String to Float
The string "20.5"
is converted to the float 20.5
.
Example 6: Boolean Conversion
In Python, the following values are considered False when converted to boolean:
0
(integer)0.0
(float)""
(empty string)[]
(empty list)None
All other values are considered True.
Conclusion
Type conversion is an essential concept in Python. Understanding when and how to convert between data types helps you avoid errors and allows you to manipulate data effectively.
Implicit Type Conversion happens automatically by Python when necessary.
Explicit Type Conversion requires you to use built-in functions to convert data types manually.
Keep practicing these conversions to build a strong foundation for your Python programs. Happy Coding at codeswithpankaj.com! 🚀
Last updated