Python Basics: Data Types, Variables, and Dynamic Typing

онлайн тренажер по питону

Data Types and Variables in Python: A Detailed Guide (2025)

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

Basic Built-in Data Types in Python

Python offers a wide range of built-in data types that 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 = 10print(type(x))  # Output: <class 'int'>
  • float: Floating-point numbers (e.g., 3.14, -2.5, 0.0).
    y = 3.14print(type(y))  # Output: <class 'float'>
  • complex: Complex numbers (e.g., 2 + 3j, -1 - 1j).
    z = 2 + 3jprint(type(z))  # Output: <class 'complex'>

Boolean

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

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

String

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

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

List

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

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

Lists allow you to add, remove, and modify elements.

Tuple

Tuples are immutable collections of elements, similar to lists.

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

Tuples are used when it is necessary to guarantee that the collection of elements will not be changed.

Set

Sets are unordered collections of unique elements.

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

Sets are used for storing unique values and performing 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 for storing and accessing data by key.

Additional Data Types

In addition to the basic data types, Python has other useful types:

  • NoneType: A special type representing the absence of a value (None).
    result = Noneprint(type(result))  # Output: <class 'NoneType'>
  • bytes and bytearray: Used for working with binary data.
  • range: Represents a range of numbers, often used in loops.

Похожие статьи

Книги по Python