Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Комбінування Умов | Умовні Оператори
Вступ до Python

bookКомбінування Умов

Спираючись на ваше розуміння булевих значень, ми розглянемо, як поєднувати кілька умов у Python. Це вміння дозволяє програмам приймати ще більш точні рішення, перевіряючи декілька критеріїв одночасно. Подивіться, як Олексій поєднує кілька умов для прийняття кращих рішень під час роботи в продуктовому магазині:

Розуміння поєднаних умов

У Python можна поєднувати умови за допомогою логічних операторів: and, or та not. Ці оператори дозволяють створювати складені умови, які перевіряють кілька булевих виразів.

  • and: повертає True, якщо обидві умови є True;
  • or: повертає True, якщо хоча б одна з умов є True;
  • not: повертає True, якщо умова є False (і навпаки).

Приклад застосування

Поєднаємо умови, щоб перевірити, чи товар є швидкопсувним ТА має великий залишок на складі, використовуючи оператор and:

12345678910111213
# Define the perishable and stock status conditions is_perishable = True item_quantity = 110 perishable_highStockRisk = 100 # Using the (and) operator to combine two conditions # The first condition (`is_perishable`) checks if the item is perishable # The second condition (`item_quantity >= perishable_highStockRisk`) checks if the item is high in stock # The `consider_discount` variable will become `True` only if both conditions are `True` consider_discount = is_perishable and (item_quantity >= perishable_highStockRisk) # Print the result print("Is the item perishable and high in stock?", consider_discount)
copy

Тепер об'єднаємо умови, щоб перевірити, чи є товар сезонним АБО святковим, використовуючи оператор or:

12345678910
# Define the seasonal and holiday status conditions seasonal_item = False holiday_item = True # Combine the conditions to check if the item is seasonal or discounted # (`temporary_stock`) will become `True` if either condition `seasonal_item` OR `holiday_item` is `True` temporary_stock = seasonal_item or holiday_item # Print the result print("Is this a seasonal or holiday item?", temporary_stock)
copy

Нарешті, розглянемо, як комбінувати умови, щоб перевірити, чи товар НЕ потребує зміни ціни, використовуючи оператор not:

12345678
# Define the item status condition is_perishable = True # Use the `not` operator to check if the item is NOT perishable long_shelf_life = not is_perishable # Print the result print("Does the item need to be sold quickly?", long_shelf_life)
copy
Завдання

Swipe to start coding

Оцінка, чи є товар зі знижкою або з низьким залишком на складі для визначення його придатності до акції.

  • Визначити булеву змінну movingProduct, яка дорівнює True, якщо товар або зі знижкою, або з низьким залишком на складі, використовуючи логічні оператори.
  • Створити булеву змінну promotion, яка дорівнює True, якщо товар не зі знижкою і має достатній залишок на складі.
  • Вивести повідомлення: Is the item eligible for promotion? <promotion>.

Вимоги до виводу

  • Вивести, чи підходить товар для акції: Is the item eligible for promotion? <promotion>.

Рішення

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

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

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

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

single

Запитати АІ

expand

Запитати АІ

ChatGPT

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

Suggested prompts:

Can you explain the difference between the and, or, and not operators with more examples?

How do I decide when to use each logical operator in my own code?

Can you give me a real-world scenario where combining conditions is useful?

close

bookКомбінування Умов

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

Спираючись на ваше розуміння булевих значень, ми розглянемо, як поєднувати кілька умов у Python. Це вміння дозволяє програмам приймати ще більш точні рішення, перевіряючи декілька критеріїв одночасно. Подивіться, як Олексій поєднує кілька умов для прийняття кращих рішень під час роботи в продуктовому магазині:

Розуміння поєднаних умов

У Python можна поєднувати умови за допомогою логічних операторів: and, or та not. Ці оператори дозволяють створювати складені умови, які перевіряють кілька булевих виразів.

  • and: повертає True, якщо обидві умови є True;
  • or: повертає True, якщо хоча б одна з умов є True;
  • not: повертає True, якщо умова є False (і навпаки).

Приклад застосування

Поєднаємо умови, щоб перевірити, чи товар є швидкопсувним ТА має великий залишок на складі, використовуючи оператор and:

12345678910111213
# Define the perishable and stock status conditions is_perishable = True item_quantity = 110 perishable_highStockRisk = 100 # Using the (and) operator to combine two conditions # The first condition (`is_perishable`) checks if the item is perishable # The second condition (`item_quantity >= perishable_highStockRisk`) checks if the item is high in stock # The `consider_discount` variable will become `True` only if both conditions are `True` consider_discount = is_perishable and (item_quantity >= perishable_highStockRisk) # Print the result print("Is the item perishable and high in stock?", consider_discount)
copy

Тепер об'єднаємо умови, щоб перевірити, чи є товар сезонним АБО святковим, використовуючи оператор or:

12345678910
# Define the seasonal and holiday status conditions seasonal_item = False holiday_item = True # Combine the conditions to check if the item is seasonal or discounted # (`temporary_stock`) will become `True` if either condition `seasonal_item` OR `holiday_item` is `True` temporary_stock = seasonal_item or holiday_item # Print the result print("Is this a seasonal or holiday item?", temporary_stock)
copy

Нарешті, розглянемо, як комбінувати умови, щоб перевірити, чи товар НЕ потребує зміни ціни, використовуючи оператор not:

12345678
# Define the item status condition is_perishable = True # Use the `not` operator to check if the item is NOT perishable long_shelf_life = not is_perishable # Print the result print("Does the item need to be sold quickly?", long_shelf_life)
copy
Завдання

Swipe to start coding

Оцінка, чи є товар зі знижкою або з низьким залишком на складі для визначення його придатності до акції.

  • Визначити булеву змінну movingProduct, яка дорівнює True, якщо товар або зі знижкою, або з низьким залишком на складі, використовуючи логічні оператори.
  • Створити булеву змінну promotion, яка дорівнює True, якщо товар не зі знижкою і має достатній залишок на складі.
  • Вивести повідомлення: Is the item eligible for promotion? <promotion>.

Вимоги до виводу

  • Вивести, чи підходить товар для акції: Is the item eligible for promotion? <promotion>.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

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

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

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

single

some-alt