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)

FAQs

What is a conditional statement in Python? ›

The if statement is a conditional statement in Python used to determine whether a block of code will be executed. If the program finds the condition defined in the if statement true, it will execute the code block inside the if statement.

What are the lesson objectives for conditionals? ›

Lesson objectives
  • Understand what conditional statements are, and why and when to use them in a program.
  • Learn how to use the Logic blocks 'If…then' and 'If…then…else'.
  • Practice using the Logic blocks so different conditions yield specified outcomes.

What is an example of a conditional statement? ›

Here are some examples of conditional statements:
  • Statement 1: If you work overtime, then you'll be paid time-and-a-half.
  • Statement 2: I'll wash the car if the weather is nice.
  • Statement 3: If 2 divides evenly into , then is an even number.
  • Statement 4: I'll be a millionaire when I win the lottery.
Mar 14, 2024

What does == mean in Python? ›

The “==” operator is known as the equality operator. The operator will return “true” if both the operands are equal. However, it should not be confused with the “=” operator or the “is” operator. “=” works as an assignment operator. It assigns values to the variables.

How to teach the first conditional lesson plan? ›

Lesson Procedure:
  1. share a similar word in their languages;
  2. illustrate the concept of the word if;
  3. make a poster to illustrate the concept;
  4. visualize sentences or situations using if, and then describe them;
  5. complete a Fishbone Graphic Organizer illustrating different options of a situation;

What are the 3 lesson objectives? ›

In summary, Cognitive objectives emphasize THINKING, Affective objectives emphasize FEELING and. Psychom*otor objectives emphasize ACTING.

What is meant by conditional statements? ›

A conditional statement is a statement that can be written in the form “If P then Q,” where P and Q are sentences. For this conditional statement, P is called the hypothesis and Q is called the conclusion.

What is a control statement in Python? ›

Control statements direct the flow of a Python program's execution. They introduce logic, decision-making, and looping. Key control statements in Python include if/else, for/while, break/continue, and pass.

What is a conditional operator in Python? ›

The ternary operator in Python is a one-liner conditional expression that assigns a value based on a condition. It is written as value_if_true if condition else value_if_false. a = 5. b = 10. max_value = a if a > b else b # max_value will be 10.

How to write conditional statements in Python in one line? ›

3 Ways to Write Pythonic Conditional Statements
  1. Use if/else statements in one line.
  2. Use table functions for multiple if/elif statements.
  3. Take advantage of the boolean values.
Feb 16, 2022

Top Articles
Beanz Rapper Boyfriend
Our Fellows | Duke Divinity School
Craigslist San Francisco Bay
Menards Thermal Fuse
Gamevault Agent
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
Jonathon Kinchen Net Worth
Jennette Mccurdy And Joe Tmz Photos
Paula Deen Italian Cream Cake
Ogeechee Tech Blackboard
Mivf Mdcalc
fltimes.com | Finger Lakes Times
Cincinnati Bearcats roll to 66-13 win over Eastern Kentucky in season-opener
Valentina Gonzalez Leak
The Murdoch succession drama kicks off this week. Here's everything you need to know
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Nhl Tankathon Mock Draft
Airrack hiring Associate Producer in Los Angeles, CA | LinkedIn
Evil Dead Rise Showtimes Near Pelican Cinemas
How to Watch Every NFL Football Game on a Streaming Service
Southland Goldendoodles
Naya Padkar Gujarati News Paper
The Creator Showtimes Near R/C Gateway Theater 8
Kirsten Hatfield Crime Junkie
Mynahealthcare Login
Dhs Clio Rd Flint Mi Phone Number
Downtown Dispensary Promo Code
Our 10 Best Selfcleaningcatlitterbox in the US - September 2024
Www Mydocbill Rada
Ups Drop Off Newton Ks
Greater Orangeburg
Garrison Blacksmith's Bench
Lucky Larry's Latina's
Maxpreps Field Hockey
That1Iggirl Mega
Craigslist Pets Huntsville Alabama
Empires And Puzzles Dark Chest
Bones And All Showtimes Near Johnstown Movieplex
15 Best Things to Do in Roseville (CA) - The Crazy Tourist
Lovein Funeral Obits
M Life Insider
Pro-Ject’s T2 Super Phono Turntable Is a Super Performer, and It’s a Super Bargain Too
Lcwc 911 Live Incident List Live Status
All-New Webkinz FAQ | WKN: Webkinz Newz
Craigslist Com St Cloud Mn
Unlock The Secrets Of "Skip The Game" Greensboro North Carolina
Dying Light Mother's Day Roof
Bama Rush Is Back! Here Are the 15 Most Outrageous Sorority Houses on the Row
Brutus Bites Back Answer Key
Lux Funeral New Braunfels
Edict Of Force Poe
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6289

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.