Skip to Content
Course content

2.1.2 Dynamic typing and type conversion

Python is known for its dynamic typing system and provides an easy way to perform type conversion. Understanding these concepts is crucial for writing flexible and error-free Python code.

1. Dynamic Typing in Python

In Python, dynamic typing means that you do not need to declare the type of a variable when you create it. The interpreter determines the type of the variable at runtime, based on the value it holds.

How Dynamic Typing Works

  • When you assign a value to a variable, Python automatically infers the type of that value.
  • You can reassign a variable to a different type during the program’s execution without raising an error.

Example of Dynamic Typing:

# Assigning an integer value to variable
x = 10
print(type(x))  # Output: <class 'int'>

# Reassigning variable to a string
x = "Hello"
print(type(x))  # Output: <class 'str'>

In this example:

  • The variable x initially holds an integer, and Python infers its type as int.
  • Later, x is reassigned to a string value, and Python automatically updates its type to str without any errors or type declarations.

Benefits of Dynamic Typing

  • Flexibility: You can write more concise code without having to specify the types of variables.
  • Ease of Use: You don’t need to worry about type declarations, allowing you to focus on writing the logic of your program.

However, dynamic typing can sometimes lead to issues where a variable's type is not what you expect, leading to runtime errors. This requires careful testing and validation of variable types in larger programs.

2. Type Conversion in Python

Python provides several ways to convert between different data types. This is known as type casting. Type conversion allows you to change one data type into another.

a. Implicit Type Conversion (Automatic Casting)

  • Python automatically converts one data type to another when the conversion is safe and does not result in loss of data.
  • This happens without explicit instructions from the programmer.

Example of Implicit Type Conversion:

# Implicit type conversion: int to float
x = 10  # int
y = 5.5  # float
result = x + y  # result will be automatically converted to float
print(result)  # Output: 15.5
print(type(result))  # Output: <class 'float'>
  • In this example, Python automatically converts the integer x to a float before performing the addition because y is a float. The result is then a float.

b. Explicit Type Conversion (Type Casting)

  • In certain situations, you might need to convert a variable to a different type manually, using type casting functions like int(), float(), str(), etc.
  • Python provides built-in functions for explicit conversion.

Examples of Explicit Type Conversion:

  • Convert to Integer (int()): Converts a number or a string representing a number to an integer.
    num_str = "100"
    num_int = int(num_str)
    print(num_int)  # Output: 100
    print(type(num_int))  # Output: <class 'int'>
    
  • Convert to Float (float()): Converts a number or a string to a float.
    num_str = "99.99"
    num_float = float(num_str)
    print(num_float)  # Output: 99.99
    print(type(num_float))  # Output: <class 'float'>
    
  • Convert to String (str()): Converts a value to a string.
    num = 42
    num_str = str(num)
    print(num_str)  # Output: '42'
    print(type(num_str))  # Output: <class 'str'>
    

c. Type Conversion Between Other Types:

  • List to Tuple: You can convert a list into a tuple using the tuple() function.
    lst = [1, 2, 3]
    tup = tuple(lst)
    print(tup)  # Output: (1, 2, 3)
    
  • Tuple to List: Similarly, you can convert a tuple into a list using the list() function.
    tup = (1, 2, 3)
    lst = list(tup)
    print(lst)  # Output: [1, 2, 3]
    

d. Type Conversion Errors

  • If you try to convert a value to a type that’s incompatible, Python will raise a ValueError.
    value = "Hello"
    # Trying to convert a non-numeric string to int
    num = int(value)  # Raises ValueError: invalid literal for int() with base 10: 'Hello'
    

To avoid such errors, ensure that the data you are converting is compatible with the target type.

Summary of Dynamic Typing and Type Conversion

  • Dynamic Typing: In Python, the type of a variable is determined at runtime, and you don’t need to explicitly declare it. This provides flexibility but may introduce errors if types are not carefully managed.
  • Type Conversion: Python allows you to convert between different data types using implicit (automatic) and explicit (manual) type conversion. Built-in functions like int(), float(), and str() are commonly used for explicit conversion.

By understanding dynamic typing and type conversion, you can write more flexible code that can work with various data types and perform operations efficiently.

Commenting is not enabled on this course.