Let's talk about the core concepts that we will be covering today...
First things first, Flow of Execution. What this means is that there is an order to the execution of code. You probably noticed this in the last notebook where things didn't work the way you were expecting them to until other things happened first. Let's start with a small example to show what this looks like with code. Run the below cell to see what order the code will print:
print("Hello")
print("there!")
print("It's really nice to meet you!")
Hello there! It's really nice to meet you!
In the above example, the statements are ordered. print("Hello")
will print before print("there!")
and print("It's really nice to meet you!")
will print last. Run the code below to see what happens when the print statements are rearranged:
print("there!")
print("Hello")
print("It's really nice to meet you!")
there! Hello It's really nice to meet you!
Knowing what statements will run first is not only extremely important for knowing the outcome of your programs, but also because you can change the flow of execution to produce different outcomes based on certain conditions. One way you can change the flow of execution for a program is by using if
, elif
, and else
statements. These statements are also known as conditionals.
A conditional allows for conditional execution of a single statement or a group of statements.
The first conditional that we will cover is the if
statement. This is one of the most important tools in a Computer Scientist's toolbox and after a little practice with it you'll see how useful it can be. Run the code cell below to see how a basic if
statement works:
isTrue = True # Change me to False to see what changes!
print("Above the if")
if isTrue:
print("Inside the if")
print("Below the if")
Above the if Inside the if Below the if
isTrue
to false to see what happens to the output!Important Note: The if
statement conditionally executed based on the value of isTrue
.
The next thing we need to learn is something called else
. How else
works is that when the condition in the if
statement is False
then the else
block is executed instead.
Important: when the if
block executes then the else
block does not.
Let's look at an example in code below:
isTrue = True
print("Above the if")
if isTrue:
print("Inside the if")
else:
print("Inside the else")
print("Below the if")
Above the if Inside the if Below the if
Notice that the print statement inside the if
block was executed, but the code inside the else
did not.
else
to execute.isTrue = True # Hint: maybe start here...
print("Above the if")
if isTrue:
print("Inside the if")
else:
print("Inside the else")
print("Below the if")
The final piece of the conditional puzzle is something called elif
, but before we explain the importance of elif
and when you would want to use it we need to talk about Booleans.
Booleans are a type of variable that can either be True or False - that's it. A boolean is what we use inside an if
statement, or in other words it is the condition that is checked to see if the code inside the if will execute. In the code above the variable isTrue
was a boolean!
There are other ways we can represent True
or False
besides just using the words True
or False
and the way we do that is by using Comparison Operators.
Here's the list of Comparison Operators:
Operator | What it Does |
---|---|
== | Checks if 2 things are equal. |
!= | Checks if 2 things are not equal |
< | Checks to see if a value is less than another value. |
> | Checks to see if a value is greater than another value. |
<= | Checks if a value is less than or equal to another value. |
>= | Checks if a value is greater than or equal to another value. |
var = 1
if var > 0: # Checks the condition to see if this is True and it is!
print("Hey this printed!")
Hey this printed!
Now let's resume our discussion of elif
. elif
is a way of saying "if the previous conditions were not true, then try this condition".
Let's look at an example with some code:
var = 1
if var > 2:
print("Hey this did not print because var is not greater than 1")
elif var == 1:
print("Hey this did print because 1 does equal 1!")
Hey this did print because 1 does equal 1!
if
is True.Why we need elif
:
var = 2
if var == 2:
print("Hey this prints because var equals 2")
elif var > 1:
print("Hey this did not print even though var is greater than 1")
print("this is because we used an elif")
Hey this prints because var equals 2
elif
to if
to see what is different with the output.var = 6
if var 6: # What needs to go here?
print("Hey! It passed the condition!")
File "<ipython-input-7-d7b57c8ad12b>", line 3 if var 6: # What needs to go here? ^ SyntaxError: invalid syntax
if
to execute. # Write code here...
if var >= 9:
print("Hey! It passed the condition inside the if!")
elif var <= 7:
print("Hey! It passed the condition inside the elif!")
else:
print("I guess var is something less than 9 but greater than 7...")
I guess var is something less than 9 but greater than 7...
if
condition and the elif
condition. Do this by declaring and setting a variable called var
.# Write code here...
if var >= 10:
print("Var must be something greater than 10!")
elif var <= 7:
print("Var must be less than 7!")
elif :
print("Get me to print!")
else:
print("I guess var is something less than 10 but greater than 7...")
Get me to print!
Add code to get the code inside the 2nd elif
to execute
hint: you're going to have to add 2 things...
# in this cell write some code!
if
statement that will output c if the condition var == 42 is True
. # Write some more code!
Above, copy and paste (ask for help if you don't know how) the code that you just wrote that printed The answer to the Universe?!?!?
if the condition var == 42 was True
.
Next, add an else
that prints guess we still don't know the answer to the universe!
and change the variable so that the if
doesn't execute.
my_num = 42
if my_num > 10 and my_num < 60:
print("We can have 2 conditions?!?!")
We can have 2 conditions?!?!
Note: In the above code we were able to test our variable against 2 conditions in a single if
statement by using and
. When we use and
both conditions must be True
for the code inside the if
to execute.
# Add some code here
# hint: you can do this by using 'and'
fav_num =
and
80. If it is between 40 and
80, print your favorite number. Else, print whoops, better luck next time
. # Run me!!
var = 30
if var < 0 or var >= 30:
print("var is not less than 0, but it is greater than or equal to 30")
var is not less than 0, but it is greater than or equal to 30
Important: For or
, only one of the conditions needs to evaluate to True
for the if
block to execute.
# Putting it all together...
my_favorite_number = 0 # Change me!
year_i_was_born = 0 # Change me!
# using an `if, else` statement, print whichever is bigger: my_favorite_number vs year_i_was_born
# your code here...
# using an `if, else` statement with a boolean `and`, print out whether or not my_favorite_number is between 12 and 30
# your code here...
# using an `if, else` statement with a boolean `or`, print out whether or not year_i_was_born is 2010 or 2011
# your code here...
# using an `if, elif, else` statement with a boolean operator, print out whether or not my_favorite_number is less than 8, between 8 and 24, or larger than 24
# your code here...
You are driving a little too fast, and a police officer stops you. Write code to print the result 'no ticket', 'small ticket', or 'big ticket'. If your speed is 60 or less, the result is 'no ticket'. If speed is between 61 and 80 inclusive, the result is 'small ticket'. If speed is 81 or more, the result is 'big ticket'. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. Then change the values of my_driving_speed and is_it_my_birthday to see how the result changes!
my_driving_speed = 61
is_it_my_birthday = False
# Your code here...
When squirrels get together for a party, they like to have sandwiches. A squirrel party is successful when the number of sandwiches is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of sandwiches. Print 'What a great party!' if the party is successful, otherwise print 'The party could have been better...'
number_of_cigars = 50
it_is_the_weekend = True
# Your code here...