Lesson 7: Conditionals | Learn and Practice with HolyPython.com (2024)

  • ESTIMATED TIME: 18 mins.
  • DIFFICULTY: Intermediate
  • FUNCTIONS: n/a
  • 7 EXERCISES

Conditional statements are an important pillar of programming and they work throughlogical expressions.

Thanks to conditional statements we can control the flow of execution by using certain statements. Now we will take a close look at them.

First of all, logical expressions in Python are very similar to their mathematical equivalents but they are slightly different. For example, equal sign is (==) instead of (=).

Let’s see a simple if statement example:

Used Where?

If statements helps us control the flow of execution.

They are extremely useful whenever you need a conditional execution.

Syntax do(s)

1) First line starts with if, followed by a statement

2) First line always ends with colon (:)

3) After first line code to be executed is written with indentation

4) If you use else as well, nothing comes after else except a colon (:)

5) And if you also decide to use an elif, it works similar to the if line, another statement after elif and a colon(:) at the end of the line.

Syntax don't(s)

1) Don't forget the colon (:) at the end of the first line

2) Don't forget the indent after the first line

Function : N/A

No new function will be introduced in this lesson.

Example 1

>>> if 1 == 1:
>>> print(“Hello World!”)

Hello World!”

In this example <iter> is just a variable we named. range(3) has 3 elements (0,1,2). So for each value (or iter) “Hello World!” is printed once.

If else (optional)

You can make your if statement more sophisticated by adding an else statement when needed.

Next 2 examples will clarify the implementation of this idea for you:

>>> if 1 == 1:
>>> print(“Hello World!”)
>>> else:
>>> print(“Wrong Statement”)

“Hello World!”

Else statement gets ignored because if statement is correct and program quits after printing “Hello World!”

Also from previous example you can see that usage of else is optional.

Example 3

>>> if 1 == 2:
>>> print(“Hello World!”)
>>> else:
>>> print(“Check Statement”)

“Check Statement”

If statement is False since 1 is not equal to 2. What happens is first indented line doesn’t get executed and program jumps to the else part and runs its print statement.

If Elif Else

You can also throw an elif between if and else, this will act as a second conditional statement.

Syntax wise elif works similar to the line with if. Start the line with elif followed by a statement and colon (:) in the end.

Let’s see an example:

Example 4

>>> if 1 ==2:
>>> print(“Hello World!”)
>>> elif 1==5:
>>> print(“1 is also not equal to 5”)
>>> else:
>>> print(“Both if and elif failed”)

“Both if and elif failed”

if statement is False as 1 is not equal 2. elif statement is also not True, so both if and elif’s statements get skipped. Then else’s statement gets executed and program ends.

Example 5

Let’s see another example that’s slightly different to make you fully understand how this works.

>>> if 1 ==2:
>>> print(“Hello World!”)
>>> elif 1==1:
>>> print(“1 is also not equal to 5”)
>>> else:
>>> print(“Both if and elif failed”)

“1 is also not equal to 5”

We only changed conditional statement of elif to 1==1 so that it’s True.

What happens is, program checks if 1==2 first, it’s False. Next is elif conditional statement 1==1. As soon as that happens elif statement gets executed and program ends without getting to the else part.

Example 6

Let’s make the conditional statements just a tad bit more advanced.

a = “Astronaut K”
>>> if a == “Astronaut P”:
>>> print(“Welcome Mr. P”)
>>> elif a == “Astronaut K”:
>>> print(“Welcome Miss K”)
>>> else:
>>> print(“Welcome on board”)

“Welcome Miss K”

Example 7

Here is an application where len() function gets involved. As you can see there is no limit to the application of if statements.

a = [“Singularity”]
b = [55, True, “so far”, [1,2,3]]
>>> if len(a) < : 15
>>> print(10)
>>> elif b == 4:
>>> print(100)
>>> else:
>>> print(1000)

10

Even though elif conditional is also True, program never executes that because if conditional is also True and after it’s statement is executed program ends.

More elif

One important point to mention is you can have multiple elifs in your if block. But you can only have one if and one else concerning the same block. (unless nested)

Let’s see an example:

Example 8: Automated Home

Can you program a automated home’s heating system? You already know more than you realize probably.

Let’s say we’re adjusting the heating oil for our automated home’s environment and water heating system. Ideally we need conditionally adjusted values for each season or even each month. Let’s see a perfect example to elaborate if, elif and else:

oil = 0
season = input(“please enter the season”)
>>> if season == “fall”:
>>> oil = 30
>>> print(oil)
>>> elif season == “winter”:
>>> oil = 100
>>> print(oil)
>>> elif season == “spring”:
>>> oil = 20
>>> print(oil)
>>> elif season == “summer”:
>>> oil = 10
>>> print(oil)
>>> else:
>>> print(“you didn’t enter a valid season!”)

100

Assuming the user entered “winter”. Program prints: 60.

Tips

Here are the logical expressions in Python:

1- Equals: a == b
2- Not Equals: a != b
3- Less than: a < b
4- Less than or equal to: a <= b
5- Greater than: a > b
6- Greater than or equal to: a >= b

Example 9: Lucky Home

Let’s use one of the logical expressions from above:

>>> oil = 150
>>> if oil >= 101:
>>> print(“You have excess oil.”)

‘You have excess oil’

Advanced Concepts 1

1- Nested if can be very handy in situations where you need to expand on the first conditional statement.

It simply requires a second or third if statement with indentation after the first one.

Let’s see an example.

Example 10

if else nested inside an if else block.

>>> a = False
>>> b = “Adam”
>>> if a == False:
>>> if b == “Adam”:
>>> a = True
>>> else:
>>> b = “Jess”
>>> else:
>>> a = False
>>> print(a)

True

Advanced Concepts 2

Negative if is a simple twist to the regular if statement.

Simply add a not after the if keyword as following and the whole statement will act oppositely, i.e.:

if not 1==1:

Let’s see an example.

Example 11

Getting the second last element:

>>> a = False
>>> if not 1==2:
>>> a=True

>>> print(a)

True

First thing to note is variable a is initially False. As the conditional statement is executed, compiler checks if 1 is not equal 2. Which is True so a gets assigned to True.

Secondly, you might notice normal assignments are done with single equal sign but when we’re constructing conditional statements or loops (for or while) it requires a logical expression meaning equal is represented with double equal signs (==).

Example 12

Instead of negative if we could use the “not equal” logical expression (!=) as following:

>>> a = False
>>> if 1 != 2:
>>> a=True

>>> print(a)

True

First thing to note is variable a is initially False. As the conditional statement is executed, compiler checks if 1 is not equal 2. Which is True so a gets assigned to True.

Secondly, you might notice normal assignments are done with single equal sign but when we’re constructing conditional statements or loops (for or while) it requires a logical expression meaning equal is represented with double equal signs (==).

7 Exercises About Conditional Statements (if-elif-else) in Python

Next Lesson: For Loops

Lesson 7: Conditionals | Learn and Practice with HolyPython.com (2024)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6030

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.