Py Chapter 2 Topic 5
Py Chapter 2 Topic 5
Py Chapter 2 Topic 5
Type casting in Python refers to the process of converting one data type into another.
This is often necessary when performing operations that involve different types, such
as combining numbers with strings or converting input data from strings to integers.
In implicit type casting, Python automatically converts one data type into another
without any user intervention. This usually happens when you perform operations
involving two different types, and Python decides which type is safe to convert into.
Example:
python
Copy code
x = 10 # int
y = 2.5 # float
result = x + y
print(result) # 12.5
print(type(result)) # <class 'float'>
In this example, Python automatically converts the integer x to a float, allowing the
operation to proceed. The result is a float, even though one of the operands (x) was
an integer.
Python automatically converts lower data types (like int) to higher data types
(like float) to prevent data loss.
Implicit casting usually occurs when:
o Performing arithmetic operations between integers and floats.
o Assigning values to variables that involve operations between mixed
types.
Explicit type casting is when you manually convert one data type into another. This
is done using built-in functions like int(), float(), str(), etc.
Example:
Invalid Example:
a = "10.5"
b = int(a) # This will raise an error because the string
contains a decimal point
Example:
# Converting an integer to float
x = 10
y = float(x)
print(y) # 10.0
print(type(y)) # <class 'float'>
a = "abc"
b = float(a) # This will raise an error because "abc"
is not a valid float
Example:
age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.
Without converting the integer age to a string, this would raise a TypeError
because Python cannot concatenate strings and integers directly.
The list() function converts a value (like a tuple, set, or string) into a list.
Example:
The tuple() function converts a value (like a list, set, or string) into a tuple.
Example:
The set() function converts a value (like a list, tuple, or string) into a set. A set
contains only unique elements.
Example:
Sometimes, when type casting, you may encounter errors if the value you’re trying
to convert is not compatible with the target data type. For example, attempting to
convert a string containing non-numeric characters to an integer will result in a
ValueError.
Example:
x = "Hello"
y = int(x) # This will raise a ValueError
Handling Type Casting Errors Using try-except:
python
Copy code
try:
x = "Hello"
y = int(x)
except ValueError:
print("Cannot convert the string to an integer")
4. Summary