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

bookОснови Перетворення Типів

Перетворення типів дозволяє переходити між основними типами Python, щоб значення можна було порівнювати, обчислювати або відображати.

Перетворення у int

int(x) створює ціле число.

  • З int: повертає те саме число;
  • З float: відкидає дробову частину у напрямку до нуля (наприклад, int(2.9) повертає 2, int(-2.9) повертає -2);
  • З рядка: рядок має представляти ціле число (допускаються пробіли та знак).

Коректні перетворення

12345678910
# Converting different types of user input to integers age_input = " 42 " temperature_reading = 2.9 negative_balance = -2.9 print(int(age_input)) # 42 → clean string converted to int print(int(temperature_reading)) # 2 → fractional part truncated print(int(negative_balance)) # -2 → also truncates toward zero print(int("7")) # 7 → string number becomes integer print(int(" -15 ")) # -15 → handles spaces and sign
copy

Викликають ValueError

12
int("2.5") # ValueError - not an integer string int("42a") # ValueError
copy

Перетворення у float

float(x) створює число з плаваючою комою.

  • Працює для цілих чисел та рядків у десятковому або науковому форматі;
  • Кома не є десятковим роздільником у Python.

Коректні перетворення

12345678
# Converting numeric inputs for a shopping calculator quantity = 3 price_str = "2.5" discount_factor = "1e3" # scientific notation for 1000 print(float(quantity)) # 3.0 → integer converted to float print(float(price_str)) # 2.5 → string price converted to float print(float(discount_factor)) # 1000.0 → converts from scientific notation
copy

Це викликає ValueError

1
float("2,5") # ValueError - use a dot, not a comma
copy

Перетворення до str

str(x) створює людинозрозуміле текстове представлення. Для формування повідомлень рекомендується використовувати f-рядки.

12345678910
# Formatting a student's exam result student_age = 42 average_score = 3.5 print(str(student_age)) # "42" → number converted to string print(str(average_score)) # "3.5" → float converted to string student_name, final_score = "Ada", 98 report_message = f"{student_name} scored {final_score} points on the exam." print(report_message)
copy

Перетворення до bool

bool(x) підпорядковується правилам істинності Python.

  • Числа: 0 — це False, будь-яке інше число — True;
  • Рядки: "" (порожній) — це False, будь-який непорожній рядок — True (навіть "0" та "False").
123456789101112
# Checking how different user inputs behave as boolean values login_attempts = 0 notifications = 7 username = "" user_id = "0" status = "False" print(bool(login_attempts)) # False → 0 means no attempts yet print(bool(notifications)) # True → non-zero means new notifications print(bool(username)) # False → empty string means no username entered print(bool(user_id)) # True → any non-empty string is truthy print(bool(status)) # True → text "False" is still a non-empty string
copy

Помилки, яких слід уникати

  • int("2.5") викликає ValueError — спочатку використовуйте float(), потім округліть або відкиньте дробову частину;
  • Локальна звичка: "2,5" є некоректним — використовуйте "2.5";
  • Підкреслення у вхідних рядках: "1_000" є некоректним — спочатку видаліть підкреслення: "1_000".replace("_", "");
  • Неочікувана істинність: bool("0") дорівнює True — порівнюйте вміст рядка явно, наприклад, s == "0".

1. Що повертає кожен рядок?

2. Який виклик спричиняє ValueError?

3. Оберіть правильне твердження.

question-icon

Що повертає кожен рядок?

int(3.9)
int(" -8 ")

bool("0")

Натисніть або перетягніть елементи та заповніть пропуски

question mark

Який виклик спричиняє ValueError?

Select the correct answer

question mark

Оберіть правильне твердження.

Select the correct answer

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

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

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

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

Запитати АІ

expand

Запитати АІ

ChatGPT

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

bookОснови Перетворення Типів

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

Перетворення типів дозволяє переходити між основними типами Python, щоб значення можна було порівнювати, обчислювати або відображати.

Перетворення у int

int(x) створює ціле число.

  • З int: повертає те саме число;
  • З float: відкидає дробову частину у напрямку до нуля (наприклад, int(2.9) повертає 2, int(-2.9) повертає -2);
  • З рядка: рядок має представляти ціле число (допускаються пробіли та знак).

Коректні перетворення

12345678910
# Converting different types of user input to integers age_input = " 42 " temperature_reading = 2.9 negative_balance = -2.9 print(int(age_input)) # 42 → clean string converted to int print(int(temperature_reading)) # 2 → fractional part truncated print(int(negative_balance)) # -2 → also truncates toward zero print(int("7")) # 7 → string number becomes integer print(int(" -15 ")) # -15 → handles spaces and sign
copy

Викликають ValueError

12
int("2.5") # ValueError - not an integer string int("42a") # ValueError
copy

Перетворення у float

float(x) створює число з плаваючою комою.

  • Працює для цілих чисел та рядків у десятковому або науковому форматі;
  • Кома не є десятковим роздільником у Python.

Коректні перетворення

12345678
# Converting numeric inputs for a shopping calculator quantity = 3 price_str = "2.5" discount_factor = "1e3" # scientific notation for 1000 print(float(quantity)) # 3.0 → integer converted to float print(float(price_str)) # 2.5 → string price converted to float print(float(discount_factor)) # 1000.0 → converts from scientific notation
copy

Це викликає ValueError

1
float("2,5") # ValueError - use a dot, not a comma
copy

Перетворення до str

str(x) створює людинозрозуміле текстове представлення. Для формування повідомлень рекомендується використовувати f-рядки.

12345678910
# Formatting a student's exam result student_age = 42 average_score = 3.5 print(str(student_age)) # "42" → number converted to string print(str(average_score)) # "3.5" → float converted to string student_name, final_score = "Ada", 98 report_message = f"{student_name} scored {final_score} points on the exam." print(report_message)
copy

Перетворення до bool

bool(x) підпорядковується правилам істинності Python.

  • Числа: 0 — це False, будь-яке інше число — True;
  • Рядки: "" (порожній) — це False, будь-який непорожній рядок — True (навіть "0" та "False").
123456789101112
# Checking how different user inputs behave as boolean values login_attempts = 0 notifications = 7 username = "" user_id = "0" status = "False" print(bool(login_attempts)) # False → 0 means no attempts yet print(bool(notifications)) # True → non-zero means new notifications print(bool(username)) # False → empty string means no username entered print(bool(user_id)) # True → any non-empty string is truthy print(bool(status)) # True → text "False" is still a non-empty string
copy

Помилки, яких слід уникати

  • int("2.5") викликає ValueError — спочатку використовуйте float(), потім округліть або відкиньте дробову частину;
  • Локальна звичка: "2,5" є некоректним — використовуйте "2.5";
  • Підкреслення у вхідних рядках: "1_000" є некоректним — спочатку видаліть підкреслення: "1_000".replace("_", "");
  • Неочікувана істинність: bool("0") дорівнює True — порівнюйте вміст рядка явно, наприклад, s == "0".

1. Що повертає кожен рядок?

2. Який виклик спричиняє ValueError?

3. Оберіть правильне твердження.

question-icon

Що повертає кожен рядок?

int(3.9)
int(" -8 ")

bool("0")

Натисніть або перетягніть елементи та заповніть пропуски

question mark

Який виклик спричиняє ValueError?

Select the correct answer

question mark

Оберіть правильне твердження.

Select the correct answer

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

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

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

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