Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Логічні Оператори | Оператор if
Умовні Оператори в Python
course content

Зміст курсу

Умовні Оператори в Python

Умовні Оператори в Python

1. Оператор if
2. Оператор if-else
3. Оператор if-elif-else
4. Тернарний Оператор Python

book
Логічні Оператори

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

Один із підходів - це використання вкладених операторів if, як показано в прикладі:

Приклад 1:

1234567
is_adult = True has_license = True if is_adult: if has_license: print("You can drive car")
copy

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

Приклад 2:

12345
is_adult = True has_license = True if is_adult and has_license: print("You can drive car")
copy

Мова Python має 3 логічні оператори:

  1. and - умова_1 і умова_2 - працює лише тоді, коли обидві умови є True.

  2. or - умова_1 або умова_2 - працює, якщо принаймні одна з двох вказаних умов є True.

  3. not - not умова застосовується до однієї умови (не до двох, як у вище вказаних прикладах) і інвертує її значення.

python

В синтаксисі Python кожне "порожнє" значення еквівалентно False, а "не порожнє" значення еквівалентно True.

1234
steps_taken = 0 if not steps_taken: print("No steps recorded yet. Time to get moving!")
copy

Logical and

Condition with and works only if both conditions are True.

123456
steps_taken = 8000 calories_burned = 600 hydration_level = 2 if steps_taken >= 5000 and calories_burned >= 500 and hydration_level >= 2: print("Amazing! You've achieved all your fitness goals for the day.")
copy

Let's continue by examining conditional statements with multiple conditions. Imagine you've taken exams in three subjects and received the following results: math_exam = 95, english_exam = 90, programming_exam = 100. You've decided to apply to three different universities, each with its own admission requirements. Let's explore these requirements.

To enter the first university, you must have a score greater than or equal to 90 in all three subjects simultaneously. Let's see if you meet this university's criteria.

As we can see, your scores from all exams are greater than or equal to 90, so our if statement worked.

Then move on to the next university. Here the condition is different, since this is the best university in your city, your scores must be greater than or equal to 95.

12345678
# Your scores math_exam = 95 english_exam = 90 programming_exam = 100 # Checking whether you will pass to the second university if math_exam >= 95 and english_exam >= 95 and programming_exam >= 95: print('Congratulations! You are enrolled in our university')
copy

As we see that our condition is not fulfilled, since we have two objects that satisfy the condition, but the third object, namely english_exam = 90, it is less than 95. Therefore, we do not get anything as a result, and our if statement is not executed.

Moving on to the next university. Here the condition is quite simple. In order to pass here, you need to have at least one subject that has passed 100 points.

It is obvious that for this case we need to use the or operator.

1. In a fitness tracker app, you want to check if a user meets their daily step goal and calorie goal. Which logical operator should you use?

2. How would you check if the user meets at least one of their fitness goals?

3.

question mark

In a fitness tracker app, you want to check if a user meets their daily step goal and calorie goal. Which logical operator should you use?

Select the correct answer

question mark

How would you check if the user meets at least one of their fitness goals?

Select the correct answer

question mark

Select the correct answer

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

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

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

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

Запитати АІ

expand
ChatGPT

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

course content

Зміст курсу

Умовні Оператори в Python

Умовні Оператори в Python

1. Оператор if
2. Оператор if-else
3. Оператор if-elif-else
4. Тернарний Оператор Python

book
Логічні Оператори

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

Один із підходів - це використання вкладених операторів if, як показано в прикладі:

Приклад 1:

1234567
is_adult = True has_license = True if is_adult: if has_license: print("You can drive car")
copy

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

Приклад 2:

12345
is_adult = True has_license = True if is_adult and has_license: print("You can drive car")
copy

Мова Python має 3 логічні оператори:

  1. and - умова_1 і умова_2 - працює лише тоді, коли обидві умови є True.

  2. or - умова_1 або умова_2 - працює, якщо принаймні одна з двох вказаних умов є True.

  3. not - not умова застосовується до однієї умови (не до двох, як у вище вказаних прикладах) і інвертує її значення.

python

В синтаксисі Python кожне "порожнє" значення еквівалентно False, а "не порожнє" значення еквівалентно True.

1234
steps_taken = 0 if not steps_taken: print("No steps recorded yet. Time to get moving!")
copy

Logical and

Condition with and works only if both conditions are True.

123456
steps_taken = 8000 calories_burned = 600 hydration_level = 2 if steps_taken >= 5000 and calories_burned >= 500 and hydration_level >= 2: print("Amazing! You've achieved all your fitness goals for the day.")
copy

Let's continue by examining conditional statements with multiple conditions. Imagine you've taken exams in three subjects and received the following results: math_exam = 95, english_exam = 90, programming_exam = 100. You've decided to apply to three different universities, each with its own admission requirements. Let's explore these requirements.

To enter the first university, you must have a score greater than or equal to 90 in all three subjects simultaneously. Let's see if you meet this university's criteria.

As we can see, your scores from all exams are greater than or equal to 90, so our if statement worked.

Then move on to the next university. Here the condition is different, since this is the best university in your city, your scores must be greater than or equal to 95.

12345678
# Your scores math_exam = 95 english_exam = 90 programming_exam = 100 # Checking whether you will pass to the second university if math_exam >= 95 and english_exam >= 95 and programming_exam >= 95: print('Congratulations! You are enrolled in our university')
copy

As we see that our condition is not fulfilled, since we have two objects that satisfy the condition, but the third object, namely english_exam = 90, it is less than 95. Therefore, we do not get anything as a result, and our if statement is not executed.

Moving on to the next university. Here the condition is quite simple. In order to pass here, you need to have at least one subject that has passed 100 points.

It is obvious that for this case we need to use the or operator.

1. In a fitness tracker app, you want to check if a user meets their daily step goal and calorie goal. Which logical operator should you use?

2. How would you check if the user meets at least one of their fitness goals?

3.

question mark

In a fitness tracker app, you want to check if a user meets their daily step goal and calorie goal. Which logical operator should you use?

Select the correct answer

question mark

How would you check if the user meets at least one of their fitness goals?

Select the correct answer

question mark

Select the correct answer

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

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

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

Секція 1. Розділ 4
Ми дуже хвилюємося, що щось пішло не так. Що трапилося?
some-alt