Python Fundamentals: Syntax and Data Structures
A Junior Python developer should be confident in the fundamental concepts of the language. Knowledge of the basic syntax is the foundation upon which the entire career of a programmer is built.
Variables and Data Types
Python supports a variety of built-in data types, each with its own characteristics:
int— integers (e.g., 42, -7)float— floating-point numbers (3.14, -2.5)str— text strings ("Hello", 'Python')bool— logical values (True, False)list— ordered mutable collections [1, 2, 3]tuple— immutable collections (1, 2, 3)dict— dictionaries with key-value pairs {"name": "John"}set— sets of unique elements {1, 2, 3}
Conditional Statements and Loops
Managing the flow of program execution is a critical skill:
# Conditional statements
age = 25
if age >= 18:
print("Совершеннолетний")
elif age >= 13:
print("Подросток")
else:
print("Ребенок")
# Loops
for i in range(5):
print(f"Итерация {i}")
numbers = [1, 2, 3, 4, 5]
while numbers:
print(numbers.pop())
Functions and Parameters
Functions are the basis of modular programming. A Junior developer must understand different ways of passing parameters:
def calculate_discount(price, discount=0.1, *args, **kwargs):
"""Calculates the price with a discount"""
final_price = price * (1 - discount)
if kwargs.get('vip_client'):
final_price *= 0.95
return final_price
# Usage
result = calculate_discount(1000, 0.2, vip_client=True)
Working with Files
The ability to read and write files is necessary for most practical tasks:
# Reading a file
with open('data.txt', 'r', encoding='utf-8') as file:
content = file.read()
# Writing to a file
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Результат обработки")
Data Structures: Choosing the Optimal Solution
Understanding when to use each data structure distinguishes a good programmer from a beginner.
| Structure | Description | When to Use | Access Complexity |
|---|---|---|---|
| List | Ordered mutable collection | When order and changes are needed | O(1) by index |
| Tuple | Immutable ordered collection | For constant data | O(1) by index |
| Dict | Key-value pairs | Fast lookup by key | O(1) on average |
| Set | Unique elements | Removing duplicates, checking for membership | O(1) on average |
Practical Examples of Usage
# List for storing operation history
operations_history = []
operations_history.append("Creating a file")
operations_history.append("Editing")
# Tuple for coordinates (immutable)
coordinates = (10.5, 20.3)
# Dictionary for configuration
config = {
"database_url": "localhost:5432",
"debug": True,
"max_connections": 100
}
# Set for unique tags
tags = {"python", "programming", "tutorial"}
Object-Oriented Programming (OOP)
OOP is a programming paradigm without which it is difficult to work with large projects. A Junior developer must understand the basic principles.
Classes and Objects
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
def __str__(self):
return f"Счет {self.owner}: {self.__balance} руб."
# Usage
account = BankAccount("Иван Петров", 1000)
account.deposit(500)
print(account) # Счет Иван Петров: 1500 руб.
Inheritance
class SavingsAccount(BankAccount):
def __init__(self, owner, balance=0, interest_rate=0.02):
super().__init__(owner, balance)
self.interest_rate = interest_rate
def add_interest(self):
interest = self.get_balance() * self.interest_rate
self.deposit(interest)
return interest
savings = SavingsAccount("Мария Иванова", 5000, 0.03)
interest = savings.add_interest()
print(f"Начислены проценты: {interest} руб.")
Exception Handling: Protecting Against Errors
грамотная обработка ошибок — признак профессионального подхода к программированию.
Basic Exception Types
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Ошибка: деление на ноль")
return None
except TypeError:
print("Ошибка: неподходящий тип данных")
return None
except Exception as e:
print(f"Неожиданная ошибка: {e}")
return None
finally:
print("Операция деления завершена")
# Usage
result = safe_divide(10, 2) # 5.0
result = safe_divide(10, 0) # None, with an error message
Creating Custom Exceptions
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Недостаточно средств: {balance}, требуется: {amount}")
def withdraw_money(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
Working with Modules and Libraries
Modern development is impossible without using ready-made solutions and libraries.
Importing Modules
import os
import sys
from datetime import datetime, timedelta
from collections import defaultdict, Counter
# Working with paths
current_dir = os.getcwd()
file_path = os.path.join(current_dir, "data", "file.txt")
# Working with dates
now = datetime.now()
tomorrow = now + timedelta(days=1)
# Counting elements
words = ["python", "java", "python", "javascript", "python"]
word_count = Counter(words)
print(word_count) # Counter({'python': 3, 'java': 1, 'javascript': 1})
Installing and Using External Libraries
# Installation: pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
def get_page_title(url):
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
title = soup.find('title')
return title.text.strip() if title else "Заголовок не найден"
except requests.RequestException as e:
return f"Ошибка загрузки: {e}"
title = get_page_title("https://python.org")
print(title)
Version Control System Git
Git is a mandatory tool for any developer. Knowing the basic commands is critical.
Basic Git Commands
# Initializing a repository
git init
# Cloning a repository
git clone https://github.com/username/repository.git
# Adding files to the staging area
git add .
git add file.py
# Creating a commit
git commit -m "Added data processing function"
# Sending changes to the remote repository
git push origin main
# Receiving changes from the remote repository
git pull origin main
# Viewing status
git status
# Viewing commit history
git log --oneline
Working with Branches
# Creating a new branch
git branch feature-auth
# Switching to a branch
git checkout feature-auth
# Creating and switching to a branch simultaneously
git checkout -b feature-payment
# Merging a branch
git checkout main
git merge feature-auth
# Deleting a branch
git branch -d feature-auth
Code Testing
Testing is an integral part of professional development. A Junior developer must be able to write basic tests.
Unittest Module
import unittest
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
raise ValueError("Деление на ноль невозможно")
return a / b
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(2, 3), 5)
self.assertEqual(self.calc.add(-1, 1), 0)
def test_subtract(self):
self.assertEqual(self.calc.subtract(5, 3), 2)
self.assertEqual(self.calc.subtract(0, 5), -5)
def test_multiply(self):
self.assertEqual(self.calc.multiply(3, 4), 12)
self.assertEqual(self.calc.multiply(-2, 3), -6)
def test_divide(self):
self.assertEqual(self.calc.divide(10, 2), 5)
with self.assertRaises(ValueError):
self.calc.divide(10, 0)
if __name__ == '__main__':
unittest.main()
Pytest - A Modern Alternative
# pip install pytest
def test_list_operations():
# Element addition test
my_list = [1, 2, 3]
my_list.append(4)
assert my_list == [1, 2, 3, 4]
# Element removal test
my_list.remove(2)
assert 2 not in my_list
# List length test
assert len(my_list) == 3
def test_string_operations():
text = "Hello, World!"
assert text.upper() == "HELLO, WORLD!"
assert text.lower() == "hello, world!"
assert text.replace("World", "Python") == "Hello, Python!"
Basics of Working with Databases
Most applications work with data, so knowing SQL and being able to interact with databases is critical.
SQLite - Built-in Database
import sqlite3
from contextlib import contextmanager
@contextmanager
def get_db_connection(db_path):
conn = sqlite3.connect(db_path)
try:
yield conn
finally:
conn.close()
class UserRepository:
def __init__(self, db_path):
self.db_path = db_path
self.create_table()
def create_table(self):
with get_db_connection(self.db_path) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
age INTEGER
)
''')
conn.commit()
def add_user(self, name, email, age):
with get_db_connection(self.db_path) as conn:
conn.execute(
'INSERT INTO users (name, email, age) VALUES (?, ?, ?)',
(name, email, age)
)
conn.commit()
def get_user_by_email(self, email):
with get_db_connection(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE email = ?', (email,))
return cursor.fetchone()
def get_all_users(self):
with get_db_connection(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
return cursor.fetchall()
# Usage
repo = UserRepository('users.db')
repo.add_user('Иван Петров', 'ivan@example.com', 25)
user = repo.get_user_by_email('ivan@example.com')
print(user)
Working with ORM (SQLAlchemy)
# pip install sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
email = Column(String(100), unique=True, nullable=False)
age = Column(Integer)
def __repr__(self):
return f"<User(name='{self.name}', email='{self.email}')>"
# Creating an engine and session
engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Adding a user
new_user = User(name='Анна Смирнова', email='anna@example.com', age=28)
session.add(new_user)
session.commit()
# Searching for users
users = session.query(User).filter(User.age > 25).all()
for user in users:
print(user)
Introduction to Web Development
Knowing the basics of web development greatly expands the capabilities of a Junior Python developer.
Flask - A Microframework for Web Applications
# pip install flask
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
# Data storage in memory
users = [
{"id": 1, "name": "Иван", "email": "ivan@example.com"},
{"id": 2, "name": "Мария", "email": "maria@example.com"}
]
@app.route('/')
def home():
return render_template('index.html')
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(users)
@app.route('/api/users', methods=['POST'])
def add_user():
data = request.get_json()
new_user = {
"id": len(users) + 1,
"name": data.get('name'),
"email": data.get('email')
}
users.append(new_user)
return jsonify(new_user), 201
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user:
return jsonify(user)
return jsonify({"error": "Пользователь не найден"}), 404
if __name__ == '__main__':
app.run(debug=True)
Django - A Full-Featured Framework
# pip install django
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
# views.py
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Product
def product_list(request):
products = Product.objects.all()
return render(request, 'products/list.html', {'products': products})
def product_detail(request, product_id):
product = get_object_or_404(Product, id=product_id)
return render(request, 'products/detail.html', {'product': product})
def api_products(request):
products = list(Product.objects.values())
return JsonResponse(products, safe=False)
Working with APIs and HTTP Requests
Modern applications often integrate with external services via APIs.
Creating an HTTP Client
import requests
import json
from datetime import datetime
class APIClient:
def __init__(self, base_url, api_key=None):
self.base_url = base_url
self.session = requests.Session()
if api_key:
self.session.headers.update({'Authorization': f'Bearer {api_key}'})
def get(self, endpoint, params=None):
url = f"{self.base_url}/{endpoint}"
try:
response = self.session.get(url, params=params, timeout=10)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Ошибка запроса: {e}")
return None
def post(self, endpoint, data=None):
url = f"{self.base_url}/{endpoint}"
try:
response = self.session.post(url, json=data, timeout=10)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Ошибка запроса: {e}")
return None
# Usage
client = APIClient('https://jsonplaceholder.typicode.com')
posts = client.get('posts')
if posts:
print(f"Получено {len(posts)} постов")
new_post = {
'title': 'Новый пост',
'body': 'Содержимое поста',
'userId': 1
}
created_post = client.post('posts', new_post)
if created_post:
print(f"Создан пост с ID: {created_post['id']}")
Fundamentals of Algorithms and Data Structures
Knowledge of basic algorithms helps to write efficient code and successfully pass technical interviews.
Sorting
def bubble_sort(arr):
"""Bubble sort - O(n²)"""
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def quick_sort(arr):
"""Quick sort - O(n log n) on average"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# Using built-in sorting (recommended)
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = sorted(numbers) # Creates a new list
numbers.sort() # Sorts the original list
Searching
def binary_search(arr, target):
"""Binary search - O(log n), array must be sorted"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def linear_search(arr, target):
"""Linear search - O(n)"""
for i, value in enumerate(arr):
if value == target:
return i
return -1
# Usage
numbers = [1, 3, 5, 7, 9, 11, 13, 15]
index = binary_search(numbers, 7)
print(f"Элемент найден на позиции: {index}")
Working with Files and Data Formats
Handling various data formats is a common task in real projects.
JSON
import json
# Working with JSON
data = {
"name": "Иван Петров",
"age": 30,
"skills": ["Python", "JavaScript", "SQL"],
"is_active": True
}
# Serialization to JSON
json_string = json.dumps(data, ensure_ascii=False, indent=2)
print(json_string)
# Writing to a file
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# Reading from a file
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(loaded_data)
CSV
import csv
# Reading CSV
def read_csv_file(filename):
with open(filename, 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
return list(reader)
# Writing CSV
def write_csv_file(filename, data, fieldnames):
with open(filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
# Example usage
employees = [
{'name': 'Иван', 'position': 'Разработчик', 'salary': 80000},
{'name': 'Мария', 'position': 'Тестировщик', 'salary': 70000},
{'name': 'Петр', 'position': 'Аналитик', 'salary': 75000}
]
write_csv_file('employees.csv', employees, ['name', 'position', 'salary'])
loaded_employees = read_csv_file('employees.csv')
XML
import xml.etree.ElementTree as ET
# Creating XML
def create_xml():
root = ET.Element("employees")
for emp in employees:
employee = ET.SubElement(root, "employee")
name = ET.SubElement(employee, "name")
name.text = emp['name']
position = ET.SubElement(employee, "position")
position.text = emp['position']
salary = ET.SubElement(employee, "salary")
salary.text = str(emp['salary'])
tree = ET.ElementTree(root)
tree.write("employees.xml", encoding='utf-8', xml_declaration=True)
# Reading XML
def read_xml():
tree = ET.parse("employees.xml")
root = tree.getroot()
employees = []
for employee in root.findall("employee"):
emp_data = {
'name': employee.find('name').text,
'position': employee.find('position').text,
'salary': int(employee.find('salary').text)
}
employees.append(emp_data)
return employees
Asynchronous Programming
Knowing the basics of async/await is becoming increasingly important for modern Python developers.
Asyncio Basics
import asyncio
import aiohttp
import time
async def fetch_url(session, url):
"""Asynchronously retrieves data from a URL"""
try:
async with session.get(url) as response:
return await response.text()
except Exception as e:
return f"Ошибка: {e}"
async def fetch_multiple_urls(urls):
"""Asynchronously retrieves data from multiple URLs"""
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
# Comparing synchronous and asynchronous approaches
def sync_example():
start_time = time.time()
urls = ['https://httpbin.org/delay/1'] * 5
# Synchronous approach
import requests
results = []
for url in urls:
response = requests.get(url)
results.append(response.text)
end_time = time.time()
print(f"Синхронное выполнение: {end_time - start_time:.2f} секунд")
async def async_example():
start_time = time.time()
urls = ['https://httpbin.org/delay/1'] * 5
# Asynchronous approach
results = await fetch_multiple_urls(urls)
end_time = time.time()
print(f"Асинхронное выполнение: {end_time - start_time:.2f} секунд")
# Running asynchronous code
if __name__ == "__main__":
asyncio.run(async_example())
Practical Tips for Development
Creating a Portfolio
Every Junior developer should have a portfolio with real projects:
- Web scraper — a program for collecting data from websites
- API service — a simple REST API using Flask or FastAPI
- Data analyzer — a script for processing and visualizing data
- Telegram bot — an interactive bot for solving practical tasks
- Web application — a full-featured application with a database
Recommended Resources for Training
- Documentation and reference books:
- Official Python documentation
- Real Python — practical guides
- Python.org — official website with tutorials
- Platforms for practice:
- LeetCode — algorithmic problems
- HackerRank — programming problems
- Codewars — problems of various levels of complexity
- GitHub — participation in open source projects
- Books for in-depth study:
- "Automate the Boring Stuff with Python" - Al Sweigart
- "Learning Python" - Mark Lutz
- "Effective Python" - Brett Slatkin
Interview Preparation
- Technical questions:
- Explain the difference between list and tuple
- What are decorators and how do they work?
- How does the garbage collector work in Python?
- What is GIL and how does it affect performance?
- Practical tasks:
- Write a function to find all anagrams in a list of words
- Implement caching of function results
- Create a class for working with matrices
- Write a script to parse web server logs
The Path to a Middle Developer
To grow to the level of Middle Python developer, you need:
- Deep understanding of the language — decorators, context managers, metaclasses
- Knowledge of design patterns — Singleton, Factory, Observer
- Experience with frameworks — Django, Flask, FastAPI
- Understanding of application architecture — MVC, microservices, REST API
- Optimization skills — profiling, caching, working with databases
- Knowledge of infrastructure — Docker, CI/CD, cloud services
Python offers many opportunities for career growth — from web development to machine learning and data analysis. The main thing is to constantly practice, learn new technologies and not be afraid of difficult tasks.
Remember: the path of a developer is continuous learning. Each project, each solved problem brings you closer to expertise. Start small, be consistent in your training, and success will not be long in coming!
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed