Conversions in Python
In Python, you can convert data from one type to another using built-in functions or constructors provided by the
data types themselves. Here are some common type conversion methods:
1. Implicit Type Conversion:
Python automatically converts data from one type to another if it's required. For example, when you perform
operations involving different data types, Python will automatically convert one of the operands to the type of the
other operand if necessary.
x = 10
y = 3.5
z = x + y # Here, x (int) is implicitly converted to a float before addition.
2. Explicit Type Conversion (Type Casting):
You can explicitly convert data from one type to another using predefined functions or constructors.
# Integer to Float
x = 10
float_x = float(x) # Converts x to a float
print(float_x) # Output: 10.0
# Float to Integer
y = 3.5
int_y = int(y) # Converts y to an integer (truncates the decimal part)
print(int_y) # Output: 3
# Integer to String
z = 123
str_z = str(z) # Converts z to a string
print(str_z) # Output: '123'
# String to Integer
s = "456"
int_s = int(s) # Converts s to an integer
print(int_s) # Output: 456
# String to Float
float_s = float(s) # Converts s to a float
print(float_s) # Output: 456.0
3. Explicit Type Conversion with Error Handling:
- Sometimes, explicit type conversion can result in errors, especially when converting between incompatible types.
You can handle such cases using error handling techniques such as `try` and `except`.
python program
s = "hello"
try:
int_s = int(s)
print(int_s)
except ValueError:
print("Conversion to int failed.")
These are some basic techniques for type conversion in Python. Understanding how to convert data between
different types is essential for data manipulation and processing in Python programs.