Переменные и типы данных
Python -- язык с динамической типизацией. Это означает, что тип переменной определяется автоматически в момент присваивания значения, а не при объявлении. Разберём все базовые типы данных и операторы.
Переменные
В Python переменная -- это просто имя, привязанное к объекту в памяти:
# Variable assignment - binding a name to an object
x = 42
name = "Иван"
pi = 3.14159
is_active = True
# Multiple assignment
a, b, c = 1, 2, 3
# Swap values (Pythonic way)
a, b = b, a
# Same value for multiple variables
x = y = z = 0
# Augmented assignment
count = 10
count += 1 # count = count + 1 -> 11
count *= 2 # count = count * 2 -> 22
count //= 3 # count = count // 3 -> 7
Правила именования
# Valid names
user_name = "Иван" # snake_case (preferred)
_private = "hidden" # leading underscore (convention)
MAX_SIZE = 100 # UPPER_CASE for constants
camelCase = "not Pythonic" # valid but not recommended
# Invalid names
# 2name = "error" # cannot start with a digit
# my-var = "error" # hyphens not allowed
# class = "error" # reserved keyword
Целые числа (int)
Целые числа в Python имеют произвольную точность -- нет ограничения на размер:
# Integer literals
decimal = 42
binary = 0b101010 # 42 in binary
octal = 0o52 # 42 in octal
hexadecimal = 0x2A # 42 in hex
# Underscores for readability (PEP 515)
population = 7_900_000_000
budget = 1_000_000
# Arbitrary precision - no overflow!
big = 2 ** 1000 # a number with 302 digits
print(type(big)) # <class 'int'>
# Integer operations
print(17 / 5) # 3.4 - true division (returns float)
print(17 // 5) # 3 - floor division (returns int)
print(17 % 5) # 2 - modulo (remainder)
print(2 ** 10) # 1024 - exponentiation
# Built-in functions
print(abs(-42)) # 42
print(divmod(17, 5)) # (3, 2) - quotient and remainder
print(pow(2, 10)) # 1024
print(pow(2, 10, 100)) # 24 - modular exponentiation (2^10 % 100)
Конвертация
# String to int
n = int("42") # 42
n = int("2A", 16) # 42 (from hex)
n = int("101010", 2) # 42 (from binary)
# Float to int (truncates toward zero)
print(int(3.7)) # 3
print(int(-3.7)) # -3
# Int to string in different bases
print(bin(42)) # '0b101010'
print(oct(42)) # '0o52'
print(hex(42)) # '0x2a'
Числа с плавающей точкой (float)
# Float literals
pi = 3.14159
negative = -0.001
scientific = 6.022e23 # 6.022 * 10^23
small = 1.6e-19 # 1.6 * 10^-19
# Float precision issues (IEEE 754)
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False!
# Correct comparison for floats
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
# Special float values
print(float('inf')) # inf
print(float('-inf')) # -inf
print(float('nan')) # nan
print(math.isinf(float('inf'))) # True
print(math.isnan(float('nan'))) # True
# Useful math functions
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(round(3.5)) # 4 (banker's rounding)
print(round(4.5)) # 4 (banker's rounding!)
print(round(3.14159, 2)) # 3.14
Decimal для точных вычислений
from decimal import Decimal, ROUND_HALF_UP
# Exact decimal arithmetic
price = Decimal("19.99")
tax = Decimal("0.07")
total = price * (1 + tax)
print(total) # 21.3893
# Rounding with control
total_rounded = total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(total_rounded) # 21.39
# Never use float for money!
print(Decimal("0.1") + Decimal("0.2")) # 0.3 (exact!)
Логический тип (bool)
# Boolean values
is_valid = True
is_empty = False
# Booleans are integers!
print(True + True) # 2
print(False * 10) # 0
print(isinstance(True, int)) # True
# Comparison operators return booleans
print(5 > 3) # True
print(5 == 3) # False
print(5 != 3) # True
print(1 <= 1) # True
# Chained comparisons (Pythonic!)
x = 5
print(1 < x < 10) # True (equivalent to 1 < x and x < 10)
print(1 < x < 3) # False
print(0 <= x <= 100) # True
# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False
# Short-circuit evaluation
name = ""
result = name or "Anonymous" # "Anonymous" (empty string is falsy)
Истинность значений (Truthiness)
# Falsy values (evaluate to False in boolean context)
falsy_values = [
False,
0, 0.0, 0j, # zero numbers
"", b"", # empty strings/bytes
[], (), {}, # empty containers
set(), # empty set
None, # None
range(0), # empty range
]
# Everything else is truthy
truthy_values = [
True,
1, -1, 3.14, # non-zero numbers
"hello", # non-empty strings
[1, 2], (1,), # non-empty containers
{"a": 1}, # non-empty dicts
]
# Practical usage
items = [1, 2, 3]
if items: # Pythonic way to check if list is not empty
print(f"Found {len(items)} items")
name = None
display = name if name else "Гость" # Conditional expression
Строки (str)
# String literals
single = 'Привет'
double = "Мир"
multiline = """Это
многострочная
строка"""
# Raw strings (ignore escape sequences)
path = r"C:\Users\admin\new_folder"
# Escape sequences
tab = "col1\tcol2"
newline = "line1\nline2"
quote = "He said \"hello\""
# String is a sequence
word = "Python"
print(word[0]) # 'P'
print(word[-1]) # 'n'
print(word[1:4]) # 'yth'
print(len(word)) # 6
# Strings are IMMUTABLE
# word[0] = 'J' # TypeError!
new_word = 'J' + word[1:] # Create a new string: 'Jython'
None
None -- специальное значение, обозначающее отсутствие значения:
# None is a singleton
result = None
print(type(result)) # <class 'NoneType'>
# Always use 'is' to compare with None
if result is None:
print("No result")
# 'is' checks identity, '==' checks equality
x = None
print(x is None) # True (correct way)
print(x == None) # True (works but not Pythonic)
# Functions without return statement return None
def greet(name: str) -> None:
print(f"Привет, {name}!")
result = greet("Иван")
print(result) # None
type() и isinstance()
# type() returns the exact type
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(type([1, 2])) # <class 'list'>
# isinstance() checks type hierarchy (preferred!)
print(isinstance(42, int)) # True
print(isinstance(True, int)) # True (bool is a subclass of int)
print(isinstance(True, bool)) # True
print(isinstance(42, (int, float))) # True (check against multiple types)
# Why isinstance() is better than type()
print(type(True) == int) # False (exact type is bool)
print(isinstance(True, int)) # True (bool inherits from int)
Операторы
Арифметические
print(10 + 3) # 13 addition
print(10 - 3) # 7 subtraction
print(10 * 3) # 30 multiplication
print(10 / 3) # 3.333 true division
print(10 // 3) # 3 floor division
print(10 % 3) # 1 modulo
print(10 ** 3) # 1000 exponentiation
print(-10 // 3) # -4 floor rounds toward negative infinity
Побитовые
a, b = 0b1100, 0b1010 # 12 and 10
print(bin(a & b)) # 0b1000 (AND)
print(bin(a | b)) # 0b1110 (OR)
print(bin(a ^ b)) # 0b0110 (XOR)
print(bin(~a)) # -0b1101 (NOT)
print(bin(a << 2)) # 0b110000 (left shift)
print(bin(a >> 2)) # 0b11 (right shift)
Операторы присваивания
x = 10
x += 5 # x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x /= 4 # x = 6.0
x //= 2 # x = 3.0
x **= 3 # x = 27.0
x %= 10 # x = 7.0
# Walrus operator (:=) - assign and use in one expression
import re
if match := re.search(r'\d+', 'abc123def'):
print(f"Found: {match.group()}") # Found: 123
Приведение типов
# Explicit type conversion
print(int("42")) # 42
print(int(3.99)) # 3 (truncates)
print(float("3.14")) # 3.14
print(float(42)) # 42.0
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False
print(bool("hello")) # True
# List/tuple/set conversions
print(list("abc")) # ['a', 'b', 'c']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3}
print(list(range(5))) # [0, 1, 2, 3, 4]
# Complex number
z = complex(3, 4) # (3+4j)
print(z.real) # 3.0
print(z.imag) # 4.0
print(abs(z)) # 5.0 (magnitude)
Идентичность и равенство
# Identity (is) vs Equality (==)
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same value)
print(a is b) # False (different objects)
print(a is c) # True (same object)
print(id(a)) # Memory address of a
print(id(c)) # Same as id(a)
# Small integer caching (-5 to 256)
x = 256
y = 256
print(x is y) # True (cached)
x = 257
y = 257
print(x is y) # False (not cached, may vary by implementation)
Итоги
- Python использует динамическую типизацию -- тип определяется при присваивании
- Основные типы:
int,float,bool,str,None - Целые числа имеют произвольную точность
- Для денежных вычислений используйте
Decimal, неfloat - Проверяйте тип через
isinstance(), неtype() - Сравнивайте с
Noneчерезis, не== - Walrus operator
:=позволяет присвоить и использовать значение в одном выражении