Python basics: data types, variables and dynamic typing

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Python Data Types and Variables: A Comprehensive Guide (2025)

In Python, data types and variables play a crucial role in creating effective and reliable programs. Understanding the basic concepts and principles of working with them is essential for every developer, regardless of their experience level. In this article, we will take a detailed look at data types, how to declare variables, dynamic typing, and best practices for working with them in Python.

Main Built-in Data Types in Python

Python offers a wide range of built-in data types, which can be divided into several categories:

  • Numeric Types
  • Boolean
  • String
  • List
  • Tuple
  • Set
  • Dictionary

Numeric Types

Numeric data types are used to represent numbers. The following numeric types are available in Python:

  • int: Integers (e.g., 10, -5, 0).

    x = 10
    print(type(x))  # Output: <class 'int'>
    
  • float: Floating-point numbers (e.g., 3.14, -2.5, 0.0).

    y = 3.14
    print(type(y))  # Output: <class 'float'>
    
  • complex: Complex numbers (e.g., 2 + 3j, -1 - 1j).

    z = 2 + 3j
    print(type(z))  # Output: <class 'complex'>
    

Boolean

The Boolean data type represents logical values True (true) or False (false). It is used to represent conditions and logical operations.

is_active = True
print(type(is_active))  # Output: <class 'bool'>

String

Strings are sequences of characters enclosed in quotes (single or double).

name = "Alice"
print(type(name))  # Output: <class 'str'>

List

Lists are mutable collections of items that can contain items of different types.

numbers = [1, 2, 3, 4, 5]
print(type(numbers))  # Output: <class 'list'>

Lists allow you to add, delete, and modify items.

Tuple

Tuples are immutable collections of items, similar to lists.

point = (10, 20)
print(type(point))  # Output: <class 'tuple'>

Tuples are used when it is necessary to ensure that a collection of items will not be changed.

Set

Sets are unordered collections of unique items.

unique_numbers = {1, 2, 3}
print(type(unique_numbers))  # Output: <class 'set'>

Sets are used to store unique values and perform set operations (e.g., union, intersection).

Dictionary

Dictionaries are collections of "key-value" pairs.

user = {"name": "Alice", "age": 30}
print(type(user))  # Output: <class 'dict'>

Dictionaries are used to store and access data by key.

Additional Data Types

In addition to the basic data types, there are other useful types in Python:

  • NoneType: A special type representing the absence of a value (None).

    result = None
    print(type(result))  # Output: <class 'NoneType'>
    
  • bytes and bytearray: Used to work with binary data.

  • range: Represents a range of numbers, often used in loops.

    numbers = range(5) # 0, 1, 2, 3, 4
    print(type(numbers)) # <class 'range'>
    

How to Find Out the Type of a Variable?

The built-in type() function allows you to determine the type of a variable:

x = 5
print(type(x))  # Output: <class 'int'>

This is useful for debugging and checking data types in code.

Importance of Knowing Data Types

Understanding data types is critical for:

  • Correct data processing.
  • Optimizing program performance.
  • Avoiding type errors (TypeError).
  • Choosing appropriate data structures for storing information.

Declaring Variables in Python

Variables in Python are named references to objects in memory. Python is a dynamically typed language, so you do not need to explicitly specify the type of a variable when declaring it.

How to Declare a Variable

A variable in Python is declared as follows:

variable_name = value

Examples of Declaring Variables

name = "Alice"  # String
age = 30  # Integer
height = 1.75  # Floating-point number
is_active = True  # Boolean

Variable Naming Rules

  • A variable name must start with a letter or an underscore (_).
  • Letters, numbers, and the underscore character are allowed.
  • A variable name is case-sensitive (Name and name are different variables).
  • Reserved language keywords (e.g., if, else, class) cannot be used.

Examples of Incorrect Variable Names

# 2name = "Error"  # Cannot start with a number
# class = "Error"  # Reserved word

Examples of Correct Variable Names

user_name = "Alice"
_user_id = 1001
age2 = 25

Multiple Variable Assignment

Python allows you to assign values to multiple variables at once:

x, y, z = 1, 2, 3

Or assign one value to multiple variables:

a = b = c = 0

Changing the Value of a Variable

Variables can be assigned a new value at any time:

status = "online"
status = "offline"

Code Style Recommendations (PEP 8)

  • Use snake_case for variable names (e.g., user_email).
  • Give variables meaningful names to make the code easier to understand.

Dynamic Typing in Python

Dynamic typing is a characteristic of programming languages in which the type of a variable is determined at runtime, rather than at compile time.

Definition of Dynamic Typing

In Python, a variable is a reference to an object in memory, and this reference can point to an object of any type.

Example of Dynamic Typing

x = 10  # x is an int
print(type(x)) # Output: <class 'int'>
x = "Hello"  # now x is a str
print(type(x)) # Output: <class 'str'>
x = [1, 2, 3]  # now x is a list
print(type(x)) # Output: <class 'list'>

Difference Between Dynamic and Static Typing

Characteristic Dynamic Typing (Python) Static Typing (C, Java)
Type Definition At runtime At compile time
Type Change Allowed Prohibited
Explicit Type Indication Not required Required
Flexibility High Low
Probability of Errors Can cause runtime errors Most errors are caught during compilation

Examples of Dynamic Typing in Action

Assigning Different Types to One Variable

data = 42  # int
print(type(data))  # <class 'int'>
data = "Python"  # str
print(type(data))  # <class 'str'>
data = [1, 2, 3]  # list
print(type(data))  # <class 'list'>

Using a Variable Without Prior Type Declaration

user_name = "Alice"
age = 30
balance = 100.50

Pros of Dynamic Typing

  • Code Simplicity: No need to worry about variable types in advance.
  • Fast Development: Less boilerplate code, faster writing of program logic.
  • Flexibility: The same variable can be used for different data types.
  • Convenient for writing scripts and automation.

Cons of Dynamic Typing

  • Runtime Errors: The program may "crash" if you unexpectedly pass an object of the wrong type.

    def add_numbers(a, b):
        return a + b
    
    # print(add_numbers(5, "10"))  # TypeError!
    
  • More Difficult to Debug Complex Projects: Large projects require strict control over data types, otherwise hidden bugs are possible.

  • Delays in Error Detection: Errors are detected only during program execution, not during its writing.

How to Minimize Risks with Dynamic Typing

Using Manual Type Checks:

def safe_add(a, b):
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        return a + b
    else:
        raise TypeError("Both parameters must be numbers!")

print(safe_add(5, 10))  # Works
# print(safe_add(5, "10"))  # Will give an error

Using Type Hints:

From Python version 3.5 and above, a type hinting system is available, which allows you to specify the expected types of variables and function parameters.

def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("Alice"))  # Works correctly

Although Python will not strictly enforce these types at runtime, special tools such as mypy will help analyze the code and catch errors at the development stage.

Using Static Code Analysis:

Tools like:

  • mypy
  • pylint
  • pyright (for VS Code)

help to check the correctness of types and find potential errors.

Why Does Python Remain a Dynamically Typed Language?

  • The main goal of Python is to make the code simple and readable.
  • Dynamic typing lowers the entry barrier for beginners.
  • Most type errors can be easily prevented with good practices and tests.
  • Fast development is more important than strict typing in many applications, especially in scripts, web development, and data analysis.

Conclusion

Dynamic typing is a powerful tool that makes Python a flexible, convenient, and easy-to-learn programming language. However, with great freedom comes great responsibility: it is important to write clean, neat code and, if possible, use type annotations to increase the reliability of projects.

The right balance between the convenience of dynamic typing and control over data types will allow you to create high-quality and reliable applications.

News