# Это однострочный комментарий
"""
Это многострочный
комментарий (docstring)
"""
print("Hello, World!") # Вывод в консоль
name = "Alice" # Строка (str)
age = 25 # Целое число (int)
price = 19.99 # Дробное число (float)
is_student = True # Логическое значение (bool)
# Арифметические операции
result = 10 + 5 # Сложение: 15
result = 10 - 5 # Вычитание: 5
result = 10 * 5 # Умножение: 50
result = 10 / 3 # Деление: 3.333...
result = 10 // 3 # Целочисленное деление: 3
result = 10 % 3 # Остаток от деления: 1
result = 2 ** 3 # Возведение в степень: 8
# Сравнение
result = 10 == 5 # Равно: False
result = 10 != 5 # Не равно: True
result = 10 > 5 # Больше: True
result = 10 < 5 # Меньше: False
result = 10 >= 5 # Больше или равно: True
# Логические операции
result = True and False # И: False
result = True or False # ИЛИ: True
result = not True # НЕ: False
text = "Hello, Python!"
# Основные методы
text.upper() # "HELLO, PYTHON!"
text.lower() # "hello, python!"
text.strip() # Удаляет пробелы по краям
text.split(",") # ['Hello', ' Python!']
"-".join(["a","b","c"]) # "a-b-c"
text.replace("Python", "World") # Замена
len(text) # 14 (длина строки)
text[0] # 'H' (первый символ)
text[-1] # '!' (последний символ)
text[7:13] # 'Python' (срез)
# F-строки (форматирование)
name = "Alice"
age = 25
message = f"{name} is {age} years old"
fruits = ["apple", "banana", "cherry"]
# Доступ к элементам
fruits[0] # "apple" (первый)
fruits[-1] # "cherry" (последний)
fruits[1:3] # ["banana", "cherry"] (срез)
# Методы списков
fruits.append("orange") # Добавление в конец
fruits.insert(1, "grape") # Вставка по индексу
fruits.remove("banana") # Удаление элемента
popped = fruits.pop() # Удаление и возврат последнего
fruits.sort() # Сортировка
fruits.reverse() # Разворот
len(fruits) # Количество элементов
"apple" in fruits # Проверка наличия: True
# Генераторы списков (list comprehensions)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
coordinates = (10, 20)
single_tuple = (5,) # Кортеж из одного элемента (запятая обязательна!)
x, y = coordinates # Распаковка: x=10, y=20
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Доступ и операции
person["name"] # "Alice"
person.get("name") # "Alice" (безопасный доступ)
person.get("country", "USA") # "USA" (значение по умолчанию)
person["email"] = "a@mail.com" # Добавление
del person["city"] # Удаление
"name" in person # True (проверка ключа)
# Методы словарей
list(person.keys()) # ['name', 'age', 'email']
list(person.values()) # ['Alice', 25, 'a@mail.com']
list(person.items()) # [('name','Alice'), ('age',25), ...]
person.update({"age": 26, "job": "dev"}) # Обновление нескольких пар
# Генераторы словарей
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
unique_numbers = {1, 2, 3, 3, 2} # {1, 2, 3}
# Операции с множествами
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1 | set2 # Объединение: {1, 2, 3, 4, 5}
set1 & set2 # Пересечение: {3}
set1 - set2 # Разность: {1, 2}
set1 ^ set2 # Симметричная разность: {1, 2, 4, 5}
age = 18
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
# Тернарный оператор
status = "adult" if age >= 18 else "minor"
# Цикл for
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for fruit in ["apple", "banana"]:
print(fruit)
# С индексом
for index, fruit in enumerate(["apple", "banana"]):
print(f"{index}: {fruit}")
# Цикл while
count = 0
while count < 3:
print(count)
count += 1
# Управление циклами
for i in range(10):
if i == 3:
continue # Пропустить итерацию
if i == 7:
break # Выйти из цикла
print(i)
def greet(name):
"""Приветствует пользователя (docstring)"""
return f"Hello, {name}!"
result = greet("Alice") # Вызов функции
# Параметры по умолчанию
def power(base, exponent=2):
return base ** exponent
power(3) # 9 (3²)
power(3, 3) # 27 (3³)
# Произвольное число аргументов
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3) # 6
# Именованные аргументы
def create_person(**kwargs):
return kwargs
person = create_person(name="Alice", age=25)
square = lambda x: x ** 2
square(5) # 25
# Использование с map/filter
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# Чтение всего файла
with open("file.txt", "r", encoding="utf-8") as file:
content = file.read()
# Чтение построчно
with open("file.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
# Чтение всех строк в список
with open("file.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
# Запись (перезапись)
with open("output.txt", "w", encoding="utf-8") as file:
file.write("Line 1\n")
file.write("Line 2\n")
# Добавление в конец
with open("output.txt", "a", encoding="utf-8") as file:
file.write("Line 3\n")
try:
result = 10 / 0
number = int("abc")
except ZeroDivisionError:
print("Деление на ноль!")
except ValueError as e:
print(f"Ошибка значения: {e}")
except Exception as e:
print(f"Неизвестная ошибка: {e}")
else:
print("Ошибок не было")
finally:
print("Это выполнится всегда")
# Создание своих исключений
def validate_age(age):
if age < 0:
raise ValueError("Возраст не может быть отрицательным")
return age
class Dog:
# Атрибут класса (общий для всех экземпляров)
species = "Canis familiaris"
# Конструктор (инициализатор)
def __init__(self, name, age):
self.name = name # Атрибут экземпляра
self.age = age
# Метод экземпляра
def bark(self):
return f"{self.name} says woof!"
# Магический метод для строкового представления
def __str__(self):
return f"{self.name} is {self.age} years old"
# Магический метод для сравнения
def __eq__(self, other):
return self.name == other.name and self.age == other.age
# Создание объектов
dog1 = Dog("Rex", 3)
dog2 = Dog("Buddy", 5)
print(dog1.bark()) # "Rex says woof!"
print(dog1) # "Rex is 3 years old"
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Должен быть реализован в подклассе")
class Cat(Animal):
def speak(self):
return f"{self.name} says meow!"
cat = Cat("Whiskers")
print(cat.speak()) # "Whiskers says meow!"
# Математические операции
import math
math.sqrt(16) # 4.0
math.pi # 3.141592653589793
math.ceil(4.3) # 5 (округление вверх)
# Случайные числа
import random
random.randint(1, 10) # Случайное целое
random.choice(["a", "b", "c"]) # Случайный элемент
random.random() # Случайное число 0-1
# Дата и время
import datetime
now = datetime.datetime.now()
today = datetime.date.today()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
# Работа с ОС
import os
os.getcwd() # Текущая директория
os.listdir(".") # Список файлов
os.path.exists("file.txt") # Проверка существования
# Системные параметры
import sys
sys.argv # Аргументы командной строки
sys.version # Версия Python
# Работа с JSON
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data) # В строку JSON
parsed = json.loads(json_str) # Из строки JSON
# Распаковка списка
a, b, c = [1, 2, 3] # a=1, b=2, c=3
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
# Распаковка словаря
def show_info(name, age):
print(f"{name}: {age}")
person = {"name": "Alice", "age": 25}
show_info(**person) # Распаковка словаря в аргументы
import os
api_key = os.getenv("API_KEY", "default_value")
value = 42
if isinstance(value, int):
print("Это целое число")
# В терминале:
python -m venv venv # Создание
source venv/bin/activate # Активация (Linux/Mac)
venv\Scripts\activate # Активация (Windows)
pip install requests # Установка пакета
pip freeze > requirements.txt # Сохранение зависимостей
# Обмен значений
a, b = b, a
# Создание словаря из двух списков
keys = ["a", "b", "c"]
values = [1, 2, 3]
mapping = dict(zip(keys, values)) # {'a':1, 'b':2, 'c':3}
# Поиск наиболее частого элемента
from collections import Counter
most_common = Counter([1,2,2,3,3,3]).most_common(1) # [(3, 3)]
class TodoList:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append({"task": task, "done": False})
def complete_task(self, index):
if 0 <= index < len(self.tasks):
self.tasks[index]["done"] = True
def show_tasks(self):
for i, task in enumerate(self.tasks):
status = "✓" if task["done"] else "✗"
print(f"{i}. [{status}] {task['task']}")
# Использование
todo = TodoList()
todo.add_task("Изучить Python")
todo.add_task("Создать проект")
todo.complete_task(0)
todo.show_tasks()
Вы должны авторизоваться, чтобы оставлять комментарии.
Комментарии ()