Python -- один из самых популярных языков программирования в мире. Он используется в веб-разработке, науке о данных, машинном обучении, автоматизации и системном администрировании. В этой статье мы установим Python 3.14, разберём основные инструменты и напишем первую программу.
Установка Python 3.14
macOS
На macOS рекомендуется использовать Homebrew:
# Install Python 3.14
brew install [email protected]
# Verify installation
python3.14 --version
# Python 3.14.0
Linux (Ubuntu/Debian)
# Add deadsnakes PPA for latest Python versions
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.14 python3.14-venv python3.14-dev
# Verify
python3.14 --version
Windows
Скачайте установщик с python.org. Обязательно отметьте галочку "Add Python to PATH" при установке.
# Verify in PowerShell
python --version
# Python 3.14.0
Что нового в Python 3.14
Python 3.14 включает значительные улучшения:
- Улучшенные сообщения об ошибках -- ещё более понятные трейсбеки
- Deferred evaluation of annotations (PEP 649) -- ленивое вычисление аннотаций
- Template strings (PEP 750) -- новый тип строк
t"..."для безопасного шаблонирования - Улучшения производительности -- оптимизации интерпретатора
# Python 3.14: deferred annotations work naturally
from __future__ import annotations # no longer needed in 3.14
class Tree:
def add_child(self, child: Tree) -> None: # forward ref works!
self.children.append(child)
REPL -- интерактивная оболочка
REPL (Read-Eval-Print Loop) -- это интерактивный режим Python. Запустите его командой python3:
$ python3.14
Python 3.14.0 (main, Oct 2025)
>>> 2 + 2
4
>>> "Hello" + " " + "World"
'Hello World'
>>> len("Python")
6
>>> exit()
REPL в Python 3.14 поддерживает многострочное редактирование, цветную подсветку синтаксиса и автодополнение из коробки.
Полезные команды в REPL
>>> help(print) # Documentation for any function
>>> dir(str) # List all string methods
>>> type(42) # Check type of a value
<class 'int'>
Запуск скриптов
Создайте файл hello.py:
# hello.py - My first Python script
print("Привет, мир!")
print("Python", 3.14)
Запустите его:
python3.14 hello.py
# Привет, мир!
# Python 3.14
Запуск модулей с python -m
Флаг -m позволяет запускать модули Python напрямую:
# Run a module as a script
python3.14 -m http.server 8000
# Run the JSON formatter
echo '{"name":"Ivan"}' | python3.14 -m json.tool
# Run pip as a module
python3.14 -m pip install requests
# Run the built-in profiler
python3.14 -m cProfile my_script.py
# Check Python configuration
python3.14 -m sysconfig
Команда python -m ищет модуль в sys.path и выполняет его __main__.py.
Виртуальные окружения (venv)
Виртуальное окружение -- изолированная копия Python с собственным набором пакетов. Это обязательная практика для любого проекта.
# Create a virtual environment
python3.14 -m venv .venv
# Activate it (macOS/Linux)
source .venv/bin/activate
# Activate it (Windows)
.venv\Scripts\activate
# Your prompt changes to show the active env
(.venv) $ python --version
Python 3.14.0
# Install packages into the isolated environment
(.venv) $ pip install requests
# Deactivate when done
(.venv) $ deactivate
Почему venv обязателен?
- Изоляция зависимостей -- разные проекты могут требовать разные версии библиотек
- Воспроизводимость --
requirements.txtфиксирует точные версии - Чистота системы -- системный Python остаётся нетронутым
# Save current dependencies
pip freeze > requirements.txt
# Install from requirements in a new environment
pip install -r requirements.txt
Функция print()
print() -- основная функция для вывода данных:
# Basic output
print("Привет!") # Привет!
# Multiple arguments separated by space
print("Имя:", "Иван", "Возраст:", 25) # Имя: Иван Возраст: 25
# Custom separator
print("2025", "01", "15", sep="-") # 2025-01-15
# Custom ending (default is \n)
print("Loading", end="... ")
print("Done!") # Loading... Done!
# Print to a file
with open("log.txt", "w") as f:
print("Log entry", file=f)
# Flush output immediately (useful for progress indicators)
import time
for i in range(5):
print(f"\rProgress: {i+1}/5", end="", flush=True)
time.sleep(0.5)
Сигнатура print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
*objects-- произвольное количество аргументов для печатиsep-- разделитель между аргументами (по умолчанию пробел)end-- символ в конце (по умолчанию перевод строки)file-- куда писать (по умолчанию stdout)flush-- немедленно сбросить буфер
Комментарии
Python поддерживает однострочные комментарии через #:
# This is a single-line comment
x = 42 # Inline comment after code
# Multi-line comments are just
# multiple single-line comments
"""
This is a docstring, not a comment.
It's used for documentation and is accessible at runtime.
"""
def greet(name: str) -> str:
"""Return a greeting message for the given name.
Args:
name: The person's name.
Returns:
A greeting string.
"""
return f"Привет, {name}!"
# Access docstring at runtime
print(greet.__doc__)
Когда использовать комментарии
Комментарии нужны чтобы объяснить почему, а не что:
# Bad: obvious comment
x = x + 1 # increment x by 1
# Good: explains the reason
x = x + 1 # compensate for 0-based indexing in the API response
# Good: warn about non-obvious behavior
# NOTE: this dict preserves insertion order (guaranteed since Python 3.7)
config = {"host": "localhost", "port": 8080}
Структура Python-проекта
Типичная структура проекта:
my_project/
├── .venv/ # Virtual environment (not in git)
├── src/
│ └── my_project/
│ ├── __init__.py # Package marker
│ └── main.py # Entry point
├── tests/
│ ├── __init__.py
│ └── test_main.py
├── pyproject.toml # Project configuration (modern standard)
├── requirements.txt # Dependencies
└── .gitignore
Файл pyproject.toml -- современный стандарт конфигурации:
[project]
name = "my-project"
version = "0.1.0"
requires-python = ">=3.14"
dependencies = [
"requests>=2.31",
]
[tool.pytest.ini_options]
testpaths = ["tests"]
Итоги
В этой статье мы:
- Установили Python 3.14 и узнали о новых возможностях
- Научились работать с REPL и запускать скрипты
- Создали виртуальное окружение с
venv - Разобрали функцию
print()и её параметры - Изучили комментарии и docstring
- Познакомились со структурой Python-проекта
В следующей статье мы изучим переменные и типы данных Python.