Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Type Conversion and Casting

Python Type Conversion and Casting Tutorial

In Python, type conversion (also known as type casting or type coercion) is the process of converting a value from one data type to another. This tutorial will cover implicit type conversion, explicit type conversion, and common type conversion functions.

  • Implicit Type Conversion

Implicit type conversion, also known as "type coercion," is when Python automatically converts one data type to another without the programmer explicitly requesting the conversion. This typically occurs in expressions involving mixed data types.

Example:

integer_num = 10
float_num = 5.5

# Python will implicitly convert integer_num to a float before performing the addition
result = integer_num + float_num
print(result)  # Output: 15.5
print(type(result))  # Output: <class 'float'>
  • Explicit Type Conversion

Explicit type conversion, or "type casting," is when the programmer explicitly requests a data type conversion. This is done using built-in functions such as int(), float(), str(), and others.

Example:

float_num = 5.5

# Explicitly convert the float to an integer (truncating the decimal part)
integer_num = int(float_num)
print(integer_num)  # Output: 5
print(type(integer_num))  # Output: <class 'int'>
  • Common Type Conversion Functions
  • int(x): Converts x to an integer. If x is a float, the decimal part is truncated. If x is a string, the string must represent a valid integer.
float_num = 5.5
integer_num = int(float_num)
print(integer_num)  # Output: 5

string_num = "42"
integer_num = int(string_num)
print(integer_num)  # Output: 42
  • float(x): Converts x to a float. If x is an integer, it is converted to a float. If x is a string, the string must represent a valid float or integer.
integer_num = 5
float_num = float(integer_num)
print(float_num)  # Output: 5.0

string_num = "42.5"
float_num = float(string_num)
print(float_num)  # Output: 42.5
  • str(x): Converts x to a string representation.
integer_num = 42
string_num = str(integer_num)
print(string_num)  # Output: "42"
print(type(string_num))  # Output: <class 'str'>
  • list(x): Converts x to a list. x must be an iterable (e.g., string, tuple, set).
example_tuple = (1, 2, 3)
example_list = list(example_tuple)
print(example_list)  # Output: [1, 2, 3]
  • tuple(x): Converts x to a tuple. x must be an iterable (e.g., string, list, set).
example_list = [1, 2, 3]
example_tuple = tuple(example_list)
print(example_tuple)  # Output: (1, 2, 3)
  • set(x): Converts x to a set. x must be an iterable (e.g., string, list, tuple).
example_list = [1, 2, 3, 1, 2, 3]
example_set = set(example_list)
print(example_set) 
  1. Casting in Python:

    • Description: Casting refers to converting one data type into another. It allows you to change the type of a variable.
    • Example Code:
      x = 5
      y = float(x)  # Casting integer to float
      
  2. Implicit vs explicit type conversion in Python:

    • Description: Implicit conversion is done automatically by Python, while explicit conversion is done by the programmer using functions like int(), str(), etc.
    • Example Code:
      implicit_result = 5 + 3.2  # Implicit conversion from int to float
      explicit_result = int(3.2) + 5  # Explicit conversion from float to int
      
  3. Converting integers to strings in Python:

    • Description: Use the str() function to convert integers to strings.
    • Example Code:
      x = 42
      str_x = str(x)
      
  4. String to integer conversion in Python:

    • Description: Use the int() function to convert strings to integers.
    • Example Code:
      str_number = "42"
      int_number = int(str_number)
      
  5. Type casting with the int(), str(), and float() functions in Python:

    • Description: The int(), str(), and float() functions are commonly used for type casting in Python.
    • Example Code:
      x = 5.7
      int_x = int(x)
      str_x = str(x)
      
  6. List to tuple conversion in Python:

    • Description: Convert a list to a tuple using the tuple() constructor.
    • Example Code:
      my_list = [1, 2, 3]
      my_tuple = tuple(my_list)
      
  7. Python type conversion errors and handling:

    • Description: Type conversion errors, such as ValueError, may occur when casting incompatible types. Handling these errors is important.
    • Example Code:
      try:
          invalid_conversion = int("abc")
      except ValueError as e:
          print(f"Error: {e}")
      
  8. Custom type conversion functions in Python:

    • Description: Define custom functions to perform specific type conversions.
    • Example Code:
      def string_to_custom_type(s):
          # Custom logic for conversion
          return custom_type_value
      
      result = string_to_custom_type("42")