Py Chapter 2 Topic 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

TYPE CASTING IN PYTHON

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.

Python supports two types of type casting:

1. Implicit Type Casting (done automatically by Python)


2. Explicit Type Casting (done manually by the programmer)

1. Implicit Type Casting

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.

When Implicit Type Casting Happens:

 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.

2. Explicit Type Casting

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.

The most commonly used explicit type casting functions are:

 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 a value (such as a tuple) to a list.
 tuple(): Converts a value (such as a list) to a tuple.
 set(): Converts a value (such as a list or tuple) to a set.

2.1. int() – Convert to Integer


The int() function converts a value to an integer.

Example:

# Converting a float to int


x = 5.7
y = int(x)
print(y) # 5
print(type(y)) # <class 'int'>

# Converting a string to int


z = "10"
num = int(z)
print(num) # 10
print(type(num)) # <class 'int'>

Note: When converting a float to an integer, the fractional part is discarded


(truncated).

Invalid Example:

a = "10.5"
b = int(a) # This will raise an error because the string
contains a decimal point

2.2. float() – Convert to Float

The float() function converts a value to a floating-point number.

Example:
# Converting an integer to float
x = 10
y = float(x)
print(y) # 10.0
print(type(y)) # <class 'float'>

# Converting a string to float


z = "3.14"
num = float(z)
print(num) # 3.14
print(type(num)) # <class 'float'>
Invalid Example:

a = "abc"
b = float(a) # This will raise an error because "abc"
is not a valid float

2.3. str() – Convert to String

The str() function converts a value to a string.

Example:

# Converting an integer to string


x = 123
y = str(x)
print(y) # "123"
print(type(y)) # <class 'str'>

# Converting a float to string


z = 45.67
num = str(z)
print(num) # "45.67"
print(type(num)) # <class 'str'>
Use Case: Concatenating Strings and Numbers

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.

2.4. list() – Convert to List

The list() function converts a value (like a tuple, set, or string) into a list.

Example:

# Converting a tuple to a list


tuple_value = (1, 2, 3)
list_value = list(tuple_value)
print(list_value) # [1, 2, 3]
print(type(list_value)) # <class 'list'>

# Converting a string to a list of characters


string_value = "hello"
char_list = list(string_value)
print(char_list) # ['h', 'e', 'l', 'l', 'o']
2.5. tuple() – Convert to Tuple

The tuple() function converts a value (like a list, set, or string) into a tuple.

Example:

# Converting a list to a tuple


list_value = [1, 2, 3]
tuple_value = tuple(list_value)
print(tuple_value) # (1, 2, 3)
print(type(tuple_value)) # <class 'tuple'>

# Converting a string to a tuple of characters


string_value = "world"
char_tuple = tuple(string_value)
print(char_tuple) # ('w', 'o', 'r', 'l', 'd')

2.6. set() – Convert to Set

The set() function converts a value (like a list, tuple, or string) into a set. A set
contains only unique elements.

Example:

# Converting a list to a set


list_value = [1, 2, 3, 3, 4]
set_value = set(list_value)
print(set_value) # {1, 2, 3, 4} (duplicates removed)
print(type(set_value)) # <class 'set'>
# Converting a string to a set of characters
string_value = "banana"
char_set = set(string_value)
print(char_set) # {'a', 'b', 'n'} (unique characters)

3. Handling Errors in Type Casting

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

 Implicit type casting is done automatically by Python when combining


different data types.
 Explicit type casting allows you to manually convert between types using
functions like int(), float(), str(), etc.
 Common type casting functions include:
o int(): Convert to integer.
o float(): Convert to float.
o str(): Convert to string.
o list(), tuple(), set(): Convert to list, tuple, or set.
 Always be cautious of potential errors when converting between types,
especially when converting strings to numeric types.

Type casting is essential in Python when you need to perform operations or


comparisons between values of different types. It helps ensure compatibility and
allows you to work more effectively with different data types.

You might also like