Conditionals | BUS 104 – Python Exam

Conditionals explained

Essentially, a conditional is a switch. For example, imagine a machine that has 3 buttons:

Whenever you press the red button that says you live in Ohio, the following message appears:

Whenever you press the button that you live in Wyoming or North Dakota, the following message appears:

And lastly, whenever you press the last button, meaning you don't live in Ohio, Wyoming, or North Dakota, the following message appears:

Conditionals can do this same exact thing through the use of if, else if, and else statements. At a high level, we could translate the above machine into a conditional like so:

If you live in Ohio… message the user "Good for you, Ohio is underrated."

If you live in Wyoming or North Dakota… message the user "Oh, isn't that like by Canada?"

If you live in any other state… message the user "Please don't tell me it's Michigan... #GoBucks"

Conditionals, when a certain condition is met, enact a certain action.

Coding with conditionals

Now, let's take the state machine that we explored above and create a Python program that replicates its functionality.

Make sure to open a Trinket file to follow-along! (How to create a Trinket file?)

To start, we must first ask the user where they live. That way, we know what message to display to them later on.

state = input("What state do you live in?")

Here we're declaring a variable state

state = input("What state do you live in?")

…and assigning it to whatever value the input() returns.

state = input("What state do you live in?")

If this doesn't make sense to you, read through the input() Function | Python in 30 Minutes article to refresh yourself.

Now, let's get started writing our first conditional statement! Here is the template for an if statement:

if condition:
    code to be executed if condition is true

A good way to describe an if statement's functionality is...

If statements check if a condition is true or false. When the condition is true, it executes the code within the indented space below. When the condition is false, it does nothing and moves on.

The main thing I want you to focus on here is the condition. Conditions will either return true or false.

So, how do we write a condition that'll return either true or false? Through the use of comparison operators and logical operators!

Comparison operators

Comparison operators are used to determine whether or not a condition returns true or false.

For example, imagine being asked:

Is your age equal to 18 years old?

This is essentially a conditional, as you're expected to answer either yes (true) or no (false).

The word "equal" serves as the comparison operator in this conditional.

Is your age equal to 18 years old?

It shows us what the relationship between age and value should be for the question to return true. They should be equal to each other.

Still confused? Go through this list of all the common comparison operators and examples of each. It should clear things up for you.

OperatorDescriptionExample (num = 1)
==__ equals __"num == 1"
True. "1 equals 1" is a true statement.
!=__ does not equal __"num != 1"
False. "1 does not equal 1" is a false statement.
>__ is greater than __"num > 0"
True. "1 is greater than 0" is a true statement.
<__ is less than __"num < 0"
False. "1 is less than 0" is a false statement.
>=__ is greater than or equal to __"num >= 2"
False. "1 is greater than or equal to 2" is a false statement.
<=__ is less than or equal to __"num <= 1"
True. "1 is less than or equal to 1" is a true statement.

Logical operators

Logical operators are used to join together multiple conditions.

For example, what if you were asked:

Is your age equal to 18 years old and does your state of residence equal Nebraska?

Although this is a single question, it actually contains 2 conditions:

First...

Is your age equal to 18 years old and does your state of residence equal Nebraska?

Second...

Is your age equal to 18 years old and does your state of residence equal Nebraska?

We can join these two conditions with the logical operator "and".

"Is your age equal to 18 years old and does your state of residence equal Nebraska?"

Refer to this list of the 2 logical operators to get a better understanding of how to use them.

OperatorDescriptionExample (num = 1)
and<condition> and <condition>

*Both conditions must be true for the statement to return true.
"num > 3 and num < 5"
False. "1 is greater than 3 and 1 is less than 5" is a false statement.

Why? The first condition is not true.
or<condition> or <condition>

*Only one of the conditions must be true for the statement to return true.
"num === 1 or num === 2"
True. "1 equals 1 or 1 equals 2" is a true statement.

How so? Because the first condition is true.

Writing an if statement

Alright, now that we know how to use comparison and logical operators, let's return to writing our first if statement. Here's the template again:

if condition:
    code to be executed if condition is true

What's our condition going to be for the first button?

If the user's state of residence (state) is equal to "Ohio"…

state = input("What state do you live in?")

if state == "Ohio":
    code to be executed if condition is true

…print in the output "Good for you, Ohio is underrated.".

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")

Now, let's move onto the second blue button.

Writing an else if statement

The template for else if statements is pretty much the exact same as an if statement...

elif condition:
    code to be executed if condition is true

...except for one difference:

Else if statements always come after if statements. Never before.

So, what's the condition going to be for our second button?

If the value of state is equal to "Wyoming"…

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming":
    code to be executed if condition is true

…or the value of state is equal to "North Dakota"…

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming" or state == "North Dakota":
    code to be executed if condition is true

…print in the output "Oh, isn't that like by Canada?".

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming" or state == "North Dakota":
    print("Oh, isn't that like by Canada?")

First, we assess if the user lives in Ohio. If they do, we message them "Good for you, Ohio is underrated."

...
if state == "Ohio":
    print("Good for you, Ohio is underrated.")

elif state == "Wyoming" or state == "North Dakota":
    print("Oh, isn't that like by Canada?")

Next, we assess if the user lives in Wyoming or North Dakota. If they do, we message them "Oh, isn't that like by Canada?"

...
if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming" or state == "North Dakota":
    print("Oh, isn't that like by Canada?")

Lastly, let's figure out how to code the last green button.

Writing an else statement

Here's the template for else statements:

else:
    code to be executed if condition is true

They differ from if statements and else if statements in 2 big ways…

1) Else statements do not have conditions.
2) Else statements always come after if and else if statements.

Notice how they don't have a condition, just like what we said in the highlighted area above.

So, how would we write this else statement for the last, green button?

If the value of your state is anything other than "Ohio", "Wyoming", or "North Dakota"...

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming" or state == "North Dakota":
    print("Oh, isn't that like by Canada?")
else:
    code to be executed if condition is true

...print in the output "Please don't tell me it's Michigan... #GoBucks".

state = input("What state do you live in?")

if state == "Ohio":
    print("Good for you, Ohio is underrated.")
elif state == "Wyoming" or state == "North Dakota":
    print("Oh, isn't that like by Canada?")
else:
    print("Please don't tell me it's Michigan... #GoBucks")

We could legitimately type anything in the input and the else statement will be executed. Let's give this a shot.

First, type the above code into your Trinket file. It should look like this now:

Then, click the "Run" button above your code. Follow along with the slideshow below as you go through the output:

  • User types in "Ohio" and presses enter...

By typing anything other than "Ohio", "Wyoming", or "North Dakota", we're essentially pressing the third button.

Here in lies the purpose of else statements.

Else statements are always executed if none of the conditions above it are true.

One vocab term to note before moving on...

The term for a group of if, else if, and/or else statements grouped together? Conditional block.

Nested conditionals

For the sake of time, I'm not going to get into nested conditionals here. Chances are, you've got an exam you need to cram for, and nested conditionals may take up too much of your time.

However, in the case that you need to learn about them, I wrote Nested Conditionals | Python in 30 Minutes for you explaining what they are and how they work.

Practice problem

In a new Trinket file, create a Python program that asks the user for an input by asking "What is your age in years?". Save the user's age as a variable. Following the question, print whether or not they're eligible for a driver's license in the output (assuming 16 years old is minimum age). The user should be warned if they enter a negative number.

Check out the slideshow below to see how your output should look.

  • The user types a negative number and presses enter...

HINT #1: The user's input is not a string, it's an integer. Forget how to write an input that returns an integer rather than a string? Check out the input() function ...with integers template on the last page of your Python Cheat Sheet for some help!

HINT #2: Forget how to print something in the output? Check out the print() function template on the last page of your Python Cheat Sheet for some help!

age = int(input("What is your age in years?"))

if age < 0:
    print("You cannot enter a negative age!")
elif age < 16:
    print("You are younger than 16 and are not eligible for a drivers license.")
else:
    print("You are 16 or older and eligible for a drivers license.")

This is just one of the ways you could've structured this conditional block. What matters is your output is the same as above in the slideshow above. If that's the case, great job!

Confused what the "int()" is doing around our input() function? Refer to input() Function | Python in 30 Minutes.

Now that we've learned how to run code depending on a set of conditions, let's learn our first loop: the while loop! Click below to continue!

Python Cram Kit

Want to unlock (PREVIEW ONLY) content? Get your Python Cram Kit now!

ApplyPRACTICE PYTHON EXAM (PREVIEW ONLY)
ToolsPython Nerd Notes (PREVIEW ONLY)
ConceptPrint function
ConceptInput function
ConceptConcatenation
ConceptConditionals (if, elif, else)
ConceptWhile loops (PREVIEW ONLY)
ConceptFor loops (PREVIEW ONLY)
ConceptData Types (PREVIEW ONLY)
ConceptNested Conditionals (PREVIEW ONLY)
ConceptFlag Variables (PREVIEW ONLY)

Leave a Comment