w3resource

What is dynamic typing in Python?

Understanding Dynamic Typing in Python: Runtime Variable Type Handling

Python's dynamic typing allows variables to be associated with data types dynamically during runtime. While statically-typed languages require variables to have a specific data type and cannot change, Python does not require explicit type declarations for variables. Variables' data types are determined by the value they hold at any given time.

How Python handles variable types dynamically at runtime:

  • No Explicit Type Declaration: Python does not require you to specify the type of a variable when declaring it. It is possible to create a variable and assign an integer value to it without explicitly stating that it is an integer.
  • Type Inference: Python automatically determines the variable's data type based on its value. It infers the data type from the value, and this is why Python is often called a "dynamically-typed" language.
  • Data Type Can Change: Python variables can change their data type during its lifetime. If you reassign a variable to a different value type, the variable will take on the new data type.
  • Type Conversion: Python performs implicit type conversion whenever required during operations. For example, if we add an integer and a float, Python will automatically convert the integer to a float to perform the operation.

Code:


# Dynamic typing in Python
x = 200
print(x, type(x))  # Output: 200 <class 'int'>
x = "Hello, Python!"
print(x, type(x))  # Output: Hello, Python! <class 'str'>
x = 6.23
print(x, type(x))  # Output: 6.23 <class 'float'>

Output:

200 <class 'int'>
Hello, Python! <class 'str'>
6.23 <class 'float'>


Follow us on Facebook and Twitter for latest update.