Course on Python Casting with Python

Course on Python Casting

Introduction to Casting in Python

In Python, casting refers to converting a variable from one data type to another. Python is a dynamically-typed language, meaning the type of variables is determined automatically. However, it may be necessary to explicitly convert types for specific operations or to ensure type compatibility.

Common Data Types

Here are some common data types in Python:

  • int (integers)
  • float (floating-point numbers)
  • str (strings)
  • bool (booleans)
  • list (lists)
  • tuple (tuples)
  • set (sets)
  • dict (dictionaries)

Built-in Casting Functions

Python provides several built-in functions to convert data types. Here are the most commonly used ones:

  • int(): Converts to integer.
  • float(): Converts to floating-point number.
  • str(): Converts to string.
  • bool(): Converts to boolean.
  • list(): Converts to list.
  • tuple(): Converts to tuple.
  • set(): Converts to set.
  • dict(): Converts to dictionary (from a sequence of key-value pairs).

Detailed Examples

Converting to Integer (int()) 

# Convert a string to an integer
str_number = "42"
int_number = int(str_number)
print(int_number)  # Output: 42
print(type(int_number))  # Output: <class 'int'>
# Convert a float to an integer (truncates the decimal part)
float_number = 3.14
int_number_from_float = int(float_number)
print(int_number_from_float)  # Output: 3
print(type(int_number_from_float))  # Output: <class 'int'>

 Converting to Float (float()) 

# Convert a string to a float
str_number = "3.14"
float_number = float(str_number)
print(float_number)  # Output: 3.14
print(type(float_number))  # Output: <class 'float'>
# Convert an integer to a float
int_number = 7
float_number_from_int = float(int_number)
print(float_number_from_int)  # Output: 7.0
print(type(float_number_from_int))  # Output: <class 'float'>

 Converting to String (str()) 

# Convert an integer to a string
int_number = 100
str_number = str(int_number)
print(str_number)  # Output: '100'
print(type(str_number))  # Output: <class 'str'>
# Convert a float to a string
float_number = 3.14
str_float_number = str(float_number)
print(str_float_number)  # Output: '3.14'
print(type(str_float_number))  # Output: <class 'str'>

 Converting to Boolean (bool()) 

# Convert an integer to a boolean
int_number = 0
bool_value = bool(int_number)
print(bool_value)  # Output: False
int_number = 42
bool_value = bool(int_number)
print(bool_value)  # Output: True
# Convert a string to a boolean
empty_str = ""
bool_value = bool(empty_str)
print(bool_value)  # Output: False
non_empty_str = "Hello"
bool_value = bool(non_empty_str)
print(bool_value)  # Output: True

Converting to List (list()) 

# Convert a tuple to a list
tuple_data = (1, 2, 3)
list_data = list(tuple_data)
print(list_data)  # Output: [1, 2, 3]
print(type(list_data))  # Output: <class 'list'>
# Convert a string to a list of characters
str_data = "Python"
list_data = list(str_data)
print(list_data)  # Output: ['P', 'y', 't', 'h', 'o', 'n']

Converting to Tuple (tuple()) 

# Convert a list to a tuple
list_data = [1, 2, 3]
tuple_data = tuple(list_data)
print(tuple_data)  # Output: (1, 2, 3)
print(type(tuple_data))  # Output: <class 'tuple'>
# Convert a string to a tuple of characters
str_data = "Python"
tuple_data = tuple(str_data)
print(tuple_data)  # Output: ('P', 'y', 't', 'h', 'o', 'n')

Converting to Set (set()) 

# Convert a list to a set
list_data = [1, 2, 2, 3, 4]
set_data = set(list_data)
print(set_data)  # Output: {1, 2, 3, 4}
# Convert a string to a set of characters
str_data = "hello"
set_data = set(str_data)
print(set_data)  # Output: {'h', 'e', 'l', 'o'}

Converting to Dictionary (dict()) 

# Convert a list of tuples to a dictionary
list_of_tuples = [('a', 1), ('b', 2), ('c', 3)]
dict_data = dict(list_of_tuples)
print(dict_data)  # Output: {'a': 1, 'b': 2, 'c': 3}
print(type(dict_data))  # Output: <class 'dict'>

Special Cases and Common Errors

Impossible Conversions

Some conversions can fail and raise errors. For example, trying to convert a non-numeric string to an integer or float will raise an error: 

# Impossible conversion
str_data = "hello"
try:
    int_data = int(str_data)
except ValueError as e:
    print(f"Error: {e}")  # Output: invalid literal for int() with base 10: 'hello'

 Converting Complex Structures

Converting complex data structures, such as nested lists or dictionaries, requires specific handling. For example: 

# Convert a list of dictionaries to a list of tuples
list_of_dicts = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
list_of_tuples = [(d['name'], d['age']) for d in list_of_dicts]
print(list_of_tuples)  # Output: [('Alice', 30), ('Bob', 25)]

 Conclusion

Casting is a fundamental operation in Python that allows you to convert data types according to the needs of your program. By mastering these conversion functions, you can handle data more flexibly and solve many common type-related issues.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *