Type Conversion in Python
In Python, type conversion (often referred to as type casting) is the process of changing a value from one data type to another.
This is incredibly common in programming. For instance, when you ask a user for input (like their age or birth year), Python receives it as a text string. To do math with it, you must convert that string into a number first!
Python supports two main ways to convert data types:
- Implicit Type Conversion: Done automatically by the Python interpreter to prevent data loss.
- Explicit Type Conversion: Done manually by you, the programmer, using built-in functions like
int(),float(), orstr().
Let us explore both in detail!
Implicit Type Conversion (Automatic)
In safe scenarios, Python will automatically upgrade your data types behind the scenes so you do not lose any valuable details. For example, if you add a whole integer to a decimal float, Python will temporarily treat the integer as a float so the math is 100 percent correct:
Example
Output:
The result is: 15.5The data type of the result is: <class 'float'>
Python automatically converts integers to floats because it is a completely safe operation. However, Python will never automatically convert a float to an integer because that would require throwing away the decimal part (causing data loss)!
Explicit Type Conversion (Manual)
To change data types manually, you will use Python’s built-in conversion functions. Let us explore the most popular ones!
1. Converting to Integers: int()
The int() function takes a decimal number, a boolean, or a clean text representation of a number and converts it into a whole integer.
Value Error Hazard!
If you try to convert a string that does not look like a clean whole number (such as "12.5" or "hello"), Python will immediately raise a ValueError and stop. Always verify your inputs before calling int()!
2. Converting to Decimals: float()
The float() function converts whole numbers, boolean values, or numeric text strings into floating-point decimal numbers.
Let us see how it works:
Example
Output:
From integer 100: 100.0From string '3.14': 3.14From boolean True: 1.0
3. Converting to Text: str()
The str() function is highly versatile. It can convert almost any Python object into a string! This is incredibly useful when you want to join text and numbers together.
Example
Output:
My name is Alice and I am 30 years old.F-string style: My name is Alice and I am 30 years old.
4. Converting Collections
You can also convert collections of items (like lists, tuples, and sets) into each other to change their properties: