In Python, Type Casting (also known as Type Conversion) is the process of converting a variable from one data type to another. This is essential because Python is dynamically typed, and you often need to reconcile different types to perform operations (like adding a string number to an integer).
There are two primary types of conversion in Python:
This is performed automatically by the Python interpreter without any user intervention. Python converts a "smaller" data type to a "larger" data type to prevent data loss.
Example: Adding an int and a float results in a float.
num_int = 10 num_float = 1.5 # Python automatically converts num_int to float result = num_int + num_float print(result) # Output: 11.5 print(type(result)) # Output: <class 'float'>
Also known as Type Casting, this is where the user manually converts the data type using built-in functions. This is necessary when Python cannot automatically handle the conversion (e.g., converting a string "5" to an integer 5).
| Function | Description | Example |
| int() | Converts to an integer | int("10") → 10 |
| float() | Converts to a floating-point number | float(5) → 5.0 |
| str() | Converts to a string | str(100) → "100" |
| list() | Converts a sequence to a list | list("abc") → ['a', 'b', 'c'] |
| tuple() | Converts a sequence to a tuple | tuple([1, 2]) → (1, 2) |
| bool() | Converts to a boolean | bool(1) → True |
# String to Integer age_str = "25" age_int = int(age_str) print(age_int + 5) # Output: 30 # Integer to Float price = 100 price_float = float(price) print(price_float) # Output: 100.0 # Float to Integer (Note: This truncates/drops the decimal) pi = 3.99 pi_int = int(pi) print(pi_int) # Output: 3 (not 4) # Data to String score = 95 message = "Your score is " + str(score) print(message) # Output: Your score is 95
Loss of Data: Converting a float to an int removes the decimal part (it does not round).
ValueErrors: You cannot cast a string that doesn't "look" like a number into an integer.
int("10") works.
int("Apple") will raise a ValueError.
Boolean Logic: In Python, bool(0), bool(None), and bool("") (empty string) are False. Almost everything else is True.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION