Python - Built in Functions Part 1: Data Type Conversion Functions
These functions are used to convert one data type into another.
Common Functions:
int(): Converts a value to an integer.
float(): Converts a value to a floating-point number.
str(): Converts a value to a string.
list(): Converts an iterable to a list.
tuple(): Converts an iterable to a tuple.
Examples:
Convert string to integer and perform arithmetic:
num_str = "42"
num = int(num_str)
print(num + 10) # Output: 52
Convert integer to string for concatenation:
age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.
Convert range to list:
nums = list(range(5))
print(nums) # Output: [0, 1, 2, 3, 4]
Explanation:
Data type conversion functions are essential for ensuring compatibility between operations. For example, converting strings to numbers is crucial for performing arithmetic operations. Similarly, creating lists or tuples from ranges or other iterables simplifies iteration and manipulation tasks.