Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте None та Бінарні Дані | Взаємодія Між Різними Типами Даних
Типи даних у Python

bookNone та Бінарні Дані

Реальні програми часто працюють із відсутніми значеннями та сирими бінарними даними. Використовуйте None для позначення відсутності значення, а bytes або bytearray — для обробки бінарного вмісту з файлів або мереж. Дізнайтеся, коли використовувати кожен тип і як безпечно конвертувати між текстом і байтами.

None для "Відсутнє значення"

None — це єдиний спеціальний об'єкт, який означає "тут нічого немає".

12345678910111213
# Basic checks result = None email = None print("result is None:", result is None) # True print("email is None:", email is None) # True # Identity checks are the reliable way if result is None: print("No result yet") if email is not None: print("Email present") else: print("Email missing")
copy

None є хибним значенням, але такими ж є 0 та "". Віддавайте перевагу is None, коли дійсно маєте на увазі "відсутнє значення".

123
value = 0 print("not value:", not value) # True - but 0 is a valid value print("value is None:", value is None) # False - correctly distinguishes 0 from missing
copy

Значення за замовчуванням та запасні варіанти

1234567891011
x = None safe_or = x or "unknown" # replaces any falsey value safe_none_only = "unknown" if x is None else x print("x=None, x or 'unknown':", safe_or) # 'unknown' print("x=None, None-only fallback:", safe_none_only) # 'unknown' x = 0 safe_or = x or "unknown" safe_none_only = "unknown" if x is None else x print("x=0, x or 'unknown':", safe_or) # 'unknown' - maybe not desired print("x=0, None-only fallback:", safe_none_only) # 0 - preserves valid zero
copy

Функції та параметри

12345678910111213
def find_user(name): # returns None if not found return None def add_tag(text, tag=None): if tag is None: tag = "general" return f"[{tag}] {text}" user = find_user("Ada") print("user is None:", user is None) # True print(add_tag("hello")) # "[general] hello" print(add_tag("hello", tag="news")) # "[news] hello"
copy

bytes та bytearray для бінарних даних

Текст використовує str і містить символи Unicode. Бінарні дані використовують bytes або bytearray і містять сирі байтові значення від 0 до 255.

123456789
# Creating binary data b1 = b"hello" # bytes literal b2 = bytes([72, 105]) # b"Hi" buf = bytearray(b"abc") # mutable buf[0] = 65 # now b"Abc" print("b1:", b1, type(b1)) # b'hello' <class 'bytes'> print("b2:", b2, type(b2)) # b'Hi' <class 'bytes'> print("buf:", buf, type(buf)) # bytearray(b'Abc') <class 'bytearray'>
copy

Перетворення тексту та байтів: кодування та декодування

1234567
text = "café" data = text.encode("utf-8") # to bytes back = data.decode("utf-8") # back to str print("text:", text, type(text)) # café <class 'str'> print("data:", data, type(data)) # b'caf\xc3\xa9' <class 'bytes'> print("back:", back, type(back)) # café <class 'str'>
copy

Змішування тексту та байтів — недійсно без конвертації

123456789
# Non-valid operation with explicit error print try: bad = b"ID:" + "123" # bytes + str - not allowed except TypeError as e: print("TypeError when mixing bytes and str:", e) # Correct combination ok = b"ID:" + "123".encode("utf-8") print("combined bytes:", ok) # b'ID:123'
copy

Довжини можуть відрізнятися

123
ch = "é" print("len('é') as str:", len(ch)) # 1 character print("len('é' encoded):", len(ch.encode("utf-8")))# 2 bytes
copy

Файли

# Binary files yield bytes
# with open("example.png", "rb") as f:
#     blob = f.read()

1. Яка перевірка коректно визначає відсутнє значення?

2. Який рядок правильно поєднує текст із префіксом байтів?

3. Яке твердження є правильним?

question mark

Яка перевірка коректно визначає відсутнє значення?

Select the correct answer

question mark

Який рядок правильно поєднує текст із префіксом байтів?

Select the correct answer

question mark

Яке твердження є правильним?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain when to use `None` versus other falsey values?

How do I safely handle default values when `0` or `""` are valid?

Can you show more examples of converting between text and bytes?

bookNone та Бінарні Дані

Свайпніть щоб показати меню

Реальні програми часто працюють із відсутніми значеннями та сирими бінарними даними. Використовуйте None для позначення відсутності значення, а bytes або bytearray — для обробки бінарного вмісту з файлів або мереж. Дізнайтеся, коли використовувати кожен тип і як безпечно конвертувати між текстом і байтами.

None для "Відсутнє значення"

None — це єдиний спеціальний об'єкт, який означає "тут нічого немає".

12345678910111213
# Basic checks result = None email = None print("result is None:", result is None) # True print("email is None:", email is None) # True # Identity checks are the reliable way if result is None: print("No result yet") if email is not None: print("Email present") else: print("Email missing")
copy

None є хибним значенням, але такими ж є 0 та "". Віддавайте перевагу is None, коли дійсно маєте на увазі "відсутнє значення".

123
value = 0 print("not value:", not value) # True - but 0 is a valid value print("value is None:", value is None) # False - correctly distinguishes 0 from missing
copy

Значення за замовчуванням та запасні варіанти

1234567891011
x = None safe_or = x or "unknown" # replaces any falsey value safe_none_only = "unknown" if x is None else x print("x=None, x or 'unknown':", safe_or) # 'unknown' print("x=None, None-only fallback:", safe_none_only) # 'unknown' x = 0 safe_or = x or "unknown" safe_none_only = "unknown" if x is None else x print("x=0, x or 'unknown':", safe_or) # 'unknown' - maybe not desired print("x=0, None-only fallback:", safe_none_only) # 0 - preserves valid zero
copy

Функції та параметри

12345678910111213
def find_user(name): # returns None if not found return None def add_tag(text, tag=None): if tag is None: tag = "general" return f"[{tag}] {text}" user = find_user("Ada") print("user is None:", user is None) # True print(add_tag("hello")) # "[general] hello" print(add_tag("hello", tag="news")) # "[news] hello"
copy

bytes та bytearray для бінарних даних

Текст використовує str і містить символи Unicode. Бінарні дані використовують bytes або bytearray і містять сирі байтові значення від 0 до 255.

123456789
# Creating binary data b1 = b"hello" # bytes literal b2 = bytes([72, 105]) # b"Hi" buf = bytearray(b"abc") # mutable buf[0] = 65 # now b"Abc" print("b1:", b1, type(b1)) # b'hello' <class 'bytes'> print("b2:", b2, type(b2)) # b'Hi' <class 'bytes'> print("buf:", buf, type(buf)) # bytearray(b'Abc') <class 'bytearray'>
copy

Перетворення тексту та байтів: кодування та декодування

1234567
text = "café" data = text.encode("utf-8") # to bytes back = data.decode("utf-8") # back to str print("text:", text, type(text)) # café <class 'str'> print("data:", data, type(data)) # b'caf\xc3\xa9' <class 'bytes'> print("back:", back, type(back)) # café <class 'str'>
copy

Змішування тексту та байтів — недійсно без конвертації

123456789
# Non-valid operation with explicit error print try: bad = b"ID:" + "123" # bytes + str - not allowed except TypeError as e: print("TypeError when mixing bytes and str:", e) # Correct combination ok = b"ID:" + "123".encode("utf-8") print("combined bytes:", ok) # b'ID:123'
copy

Довжини можуть відрізнятися

123
ch = "é" print("len('é') as str:", len(ch)) # 1 character print("len('é' encoded):", len(ch.encode("utf-8")))# 2 bytes
copy

Файли

# Binary files yield bytes
# with open("example.png", "rb") as f:
#     blob = f.read()

1. Яка перевірка коректно визначає відсутнє значення?

2. Який рядок правильно поєднує текст із префіксом байтів?

3. Яке твердження є правильним?

question mark

Яка перевірка коректно визначає відсутнє значення?

Select the correct answer

question mark

Який рядок правильно поєднує текст із префіксом байтів?

Select the correct answer

question mark

Яке твердження є правильним?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3
some-alt