Course Content

# Conditional Statements in Python

3. Python if-elif-else Statement

4. Python Ternary Operator

Conditional Statements in Python

## Logical Operators 1/2

Previously, we explored situations involving a single condition in the if statement. Now, let's delve into scenarios where we need to evaluate multiple conditions.

One approach is to use nested `if`

statements, as demonstrated in the example:

#### Example 1:

However, relying heavily on nested `if`

conditions is not considered best practice. A seasoned developer would prefer to use logical operators instead of nesting conditions.

#### Example 2:

Python language has 3 logical operators:

`and`

- condition_1 and condition_2 - works only if both conditions are`True`

.`or`

- condition_1 or condition_2 - works if**at least one**of the two specified conditions is`True`

.`not`

-`not condition`

is applied to one condition (not two as above) and inverts its value.

In Python syntax, each "**empty"** value is equivalent to `False`

, and any **"non-empty"** value is equivalent to `True`

.

#### Example 3:

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.

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.

As we can see, we still have one subject with a score of 100. It's important to note that for the `or`

operator, it's enough for just one condition to be `True`

.

It's worth remembering that if none of the conditions are `True`

, the `if`

statement won't be executed, and you won't meet the criteria.

Now, it's time to practice!

Everything was clear?