Оператори Порівняння
Свайпніть щоб показати меню
Порівняння дозволяють програмі ставити питання з відповіддю так/ні щодо значень:
- Чи однакові ці значення?
- Чи це більше?
- Чи входить це число в діапазон?
Порівняння повертає булеве значення (True або False) і є основою логіки if/while.
Основи
Python надає шість операторів порівняння (==, !=, <, <=, >, >=) для перевірки рівності та порядку між значеннями; кожне порівняння повертає True або False.
Рівність ==
Перевіряє, чи два значення однакові.
1234567saved_pin = 1234 entered_pin = 1234 print(saved_pin == entered_pin) # True → user entered the correct PIN stored_email = "support@codefinity.com" input_email = "Support@codefinity.com" print(stored_email == input_email) # False → case matters in string comparison
= присвоює значення змінній, тоді як == порівнює два значення.
Нерівність !=
Перевіряє, чи два значення різні.
1234567user_id_1 = 105 user_id_2 = 203 print(user_id_1 != user_id_2) # True → users have different IDs username_1 = "alex" username_2 = "alex" print(username_1 != username_2) # False → usernames match
Більше ніж >
True, якщо ліве значення строго більше за праве.
123456789# Comparing delivery times in minutes estimated_time = 7 actual_time = 9 print(estimated_time > actual_time) # False → delivery took longer than expected # Comparing two product ratings rating_product_a = 12 rating_product_b = 3 print(rating_product_a > rating_product_b) # True → product A has a higher rating
Менше ніж <
Повертає True, якщо ліве значення строго менше за праве.
123456789# Comparing user's age with the minimum required age user_age = 17 min_age = 18 print(user_age < min_age) # True → user is too young to access the service # Comparing names alphabetically first_name = "Alice" second_name = "Bob" print(first_name < second_name) # True → "Alice" comes before "Bob" alphabetically
Більше або дорівнює >=
Повертає True, якщо ліве значення більше або дорівнює правому.
123456789# Checking if a student reached the passing score student_score = 7 passing_score = 7 print(student_score >= passing_score) # True → student passed the test # Comparing two package weights before shipping package_weight = 4 min_weight_required = 9 print(package_weight >= min_weight_required) # False → package is too light
Менше або дорівнює <=
True, якщо ліве значення менше або дорівнює правому.
123456789# Checking if an order total qualifies for a discount limit order_total = 10 discount_limit = 9 print(order_total <= discount_limit) # False → total exceeds the discount limit # Verifying if a student arrived on time (in minutes) arrival_time = 5 deadline_time = 5 print(arrival_time <= deadline_time) # True → student arrived right on time
Ланцюгові порівняння
Python дозволяє природно записувати діапазони:
0 < x < 10 означає "x більше 0 та менше 10".
В основі це працює як (0 < x) and (x < 10).
1234567# Checking if the temperature is within a comfortable range temperature = 7 print(0 < temperature < 10) # True → temperature is within the cool range # Checking if a user's rating fits the top-tier range user_rating = 7 print(5 <= user_rating <= 7) # True → rating is within the premium bracket
Такий запис є зрозумілим і дозволяє уникнути повторення x.
Порівняння рядків
Порівняння рядків є чутливими до регістру та лексикографічними (символ за символом у порядку Unicode).
123456789# Comparing user input with stored data saved_password = "Apple" typed_password = "apple" print(saved_password == typed_password) # False → passwords are case-sensitive # Sorting items alphabetically first_item = "apple" second_item = "banana" print(first_item < second_item) # True → "apple" comes before "banana" alphabetically
Для перевірки без урахування регістру спочатку нормалізуйте обидві сторони.
12345# Comparing email addresses entered in different cases email_stored = "Support@Codefinity.com" email_input = "support@codefinity.COM" print(email_stored.lower() == email_input.lower()) # True → emails match, case ignored
1. Заповніть пропуски: True або False:
2. Який єдиний вираз правильно перевіряє, що x знаходиться між 1 та 5 включно (з використанням ланцюгового порівняння)?
3. Яке порівняння рядків є істинним?
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат