Chapter 3.1.1 - if
statements¶
The most basic if
statements are used for conditional execution of python code using a single test that generates a bool
. If the bool
is True
the code that “belongs” to the if
statement is executed. If the bool
is False
, the code is ignored.
The syntax is as follows:
- Add the keyword
if
to your code:if
- Add a space and then a test that is within parentheses:
if (test)
- Add a
:
immediately after the test:if (test):
- Press enter and add code that starts 4 spaces from the left margin:
if (test):
code
In this example, code
will only run if test
is True.
This addition changes our program type from sequential to conditional. In other words, not every line of code will be executed. What lines are or are not executed are based on the requirements of your program and the logic assocated with those requirements.
For example, say you have a version of Blackboard that sends you a message saying “Great job!” whenever you get an assignment score above 90%.
score = 85
print("Great job!")
If you wrote a simple sequential program like the one above, there would be no way to control if the message is sent or not. This would result in some students who did not score a 90% to get the message.
Instead, we want to conditionally execute lines of code using if
statements.
Back to the previous example, the requirement of the program is that “Great job!” is only sent when an assignment score exceeds 90%. This is the “english” version of the requirements. To convert this into a Python version, you need to translate what “exceeds 90%” means, and note that you should probably use a >
operator. Once you figure this out, you need to determine what goes on the left of the operator and what goes on the right. Typically, we put the variable or value being “tested” on the left, and the value it is being tested against on the right:
score > 90
Recalling our discussion on bool
, the following examples would result in either True or False.
False
if score is 90 or less:
score = 85
print(score > 90) #output is False, since 85 is not greater than 90
True
if score is greater than 90:
score = 95
print(score > 90) #output is True, since 95 is greater than 90
Next we need to add the test to the if
syntax as defined above and add indented code below the if
statement:
score = 95
if (score > 90):
print("Great job!")
Here is the code in action. Change score
to print “Great job!”:
score = 80
if (score > 90):
print("Great job!")
Notice that nothing happens if the score is not greater than 90. This is because Python ignores any code under the if
statement if the condition does not result in a bool
equal to True.
If we want to add code that always runs, we just add unindented code below or above the if
statement:
score = 95
print(f"Your score was {score}%")
if (score > 90):
print("Great job!")
print("That is all for now!")
Your score was 95%
Great job!
That is all for now!
Notice that the variable definition and the two print statements both ran even if you changed score
to something less than or equal to 90.
This can become complicated if you change a variable within the if
statement:
score = 95
if (score > 90):
print("Great job!")
score = score - 10
print(f"Your score was {score}%")
print("That is all for now!")
Great job!
Your score was 85%
That is all for now!
We can use print
statements to follow what is happening to score
.
We see that when score is greater than 90, score > 90
is True
, so the indented code is executed. It is only after the indented code is executed that the score is set equal to itself minus 10. This has no influence on the if
statement at that point.
score = 95
print("Unindented Line before the if, score = ", score)
if (score > 90):
print("Indented Line after the if, score = ", score)
print("Great job!")
print("Indented Line after the Great job!, score = ", score)
score = score - 10
print("Indented Line after the score = score - 10, score = ", score)
print("Unindented Line before your score was, score = ", score)
print(f"Your score was {score}%")
print("That is all for now!")
Unindented Line before the if, score = 95
Indented Line after the if, score = 95
Great job!
Indented Line after the Great job!, score = 95
Indented Line after the score = score - 10, score = 85
Unindented Line before your score was, score = 85
Your score was 85%
That is all for now!
Chapter 3.1.2 - if else
statements¶
There are some cases where you need one of two options to be executed, but not both.
This is called mutually exclusive code because the two options cannot both occur while the program and its variables are in a particular state. Going back to the example above, perhaps you want to send a supportive message like “Get 'em next time!” to those who do not score better than a 90.
In other words, you want to send either “Great job!” or “Get 'em next time!”, but not both. What determines what message is sent is the test score > 90
.
To do this, we simply add an else
keyword that has the same “indentation level” as the if
keyword. Under the else
, you write code that will be executed if the test results in a bool
equal to False
. We can refer to the code belonging to the if
(indented under the if
) as the “if
code block”, and the code belonging to the else
as the “else
code block”.
Change score
to see both messages.
score = 85
print(f"Your score was {score}%")
if (score > 90):
print("Great job!")
else:
print("Get 'em next time!")
print("That is all for now!")
Your score was 85%
Get 'em next time!
That is all for now!
Chapter 3.1.3 - if elif else
statements¶
You can extend this pattern by including as many elif
keywords between the if
code block and the else
code block. The elif code block test should be more permissive (easier to get a True
) than the if
code block test or the test should be mutually exclusive.
The rules of the if elif else
statement are the same as the if else
, except the only code block that will be executed is the first time a test results in True
. If none of the tests result in True
, the else
code block is executed.
What if we wanted to send “Great job!” to those with above 90, and “Good job!” to those between 81 and 90 (including 90)?
You can add a test for score > 80
. You might think that this would not work, because a score of 95, for example, would be True
for score > 90
and score > 80
. However, as stated above, the first True
will result in none of the other code blocks being executed.
Therefore, we know that elif (score > 80)
will only be considered if (score > 90)
was False
.
Try to change score
below to get every message.
score = 85
print(f"Your score was {score}%")
if (score > 90):
print("Great job!")
elif (score > 80):
print("Good job!")
elif (score > 70):
print("Average job!")
elif (score > 60):
print("Passable job!")
else:
print("Get 'em next time!")
print("That is all for now!")
Your score was 85%
Good job!
That is all for now!
3.1.4 - Indentation and whitespace¶
If you are new to programming, this might not be as hard to learn as for those who come from C++, Java, etc.
Python uses whitespace and indentation to determine what code “belongs” to what control structure (example, an if elif else
statement).
The dashes are just demonstrating “whitespace” in the example below:
if (test):
----start code here
----if it belongs to
----this if statement
The actual Python code would look something like this:
score = 85
if (score >= 90):
grade = "A"
elif (score >= 80):
grade = "B"
elif (score >= 70):
grade = "C"
else:
grade = "D"
print("Grade =", grade)
This is in contrast to C++, Java, and even javascript that use brackets to determine to what control structure the code block belongs:
Java code:
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "D";
}
System.out.println("Grade = " + grade);
How you can get it wrong.
if
statement errors¶
Case 1
Since indentation is so important, it is crucial that you pay attention to exactly how much indentation you give your code blocks.
For example, the following results in an error in Python, but would be perfectly fine in Java as long as it is within the brackets:
score = 95
if (score >= 90):
print("A")
print("Good job!")
File <string>:5
print("Good job!")
^
IndentationError: unindent does not match any outer indentation level
Case 2
Another common error is to forget the “:” after the test. This might be the first thing you would want to check if you have an error in your if
statements:
score = 95
if (score >= 90) # you forgot the ":"
print("A")
print("Good job!")
Cell In[9], line 3
if (score >= 90) # you forgot the ":"
^
SyntaxError: expected ':'
Case 3
You can also write code that is not “incorrect” from a syntax perspective, but it is incorrect from a logical perspective.
Say you wanted to only write “Good job!” if the score is better than or equal to 90.
If you do not get the indentation correct, Python will treat the code as part of the broader program and not a part of the if
statement:
score = 95
if (score >= 90):
print("A")
print("Good job!")
A
Good job!
score = 95
if (score >= 90):
print("A")
print("Good job!")
else:
Cell In[11], line 7
^
SyntaxError: incomplete input
If you want to debug your if
code, you can temporarily use a print
statement or the pass
statement, but this is only temporary:
score = 95
if (score >= 90):
print("A")
print("Good job!")
else:
pass
A
Good job!
Case 5
You cannot have a “test” for the else
block:
score = 85
if (score >= 90):
print("A")
print("Good job!")
else (score < 90):
print("Try again next time!")
Cell In[13], line 6
else (score < 90):
^
SyntaxError: expected ':'
score = 85
if (score >= 90):
print("A")
print("Good job!")
elif (score >= 80):
print("B")
print("Not bad!")
elif:
print("C")
print("Pick it up!")
else:
print("Try again next time!")
Cell In[14], line 9
elif:
^
SyntaxError: invalid syntax
Although it will not give you an error, you should end if / elif / else
statements with an else
statement.
This is because you may miss cases that are not covered by the if
and elif
blocks:
score = 55
if (score >= 90):
print("A")
print("Good job!")
elif (score >= 80):
print("B")
print("Not bad!")
elif (score >= 70):
print("C")
print("Pick it up!")
Chapter 3.1.5 - Practice¶
- Create an if/else statement to test if a score is greater than 60. Add an appropriate message.
- Create an if/else statement to test if a score is less than 60. Add an appropriate message.
- Create an if/else statement to test if a score is greater than or equal to 60. Add an appropriate message.
- Create an if/else statement to test if a score is less than or equal to 60. Add an appropriate message.
- Create an if/elif/else statement to meet the following criteria:
Water will boil into a gas at 100 C and freeze into a solid at 0 C, and will be liquid between those values. Write code blocks that say “Solid”, “Liquid”, or “Gas” based on the variable temp
.
5b. Provide an example of each possibility by changing the variable ‘temp’
- Fix all of the issues in the following
if / elif / else
using hints from the error messages.
In this case, we want to print the following:
“SEVERE” if
CAPE
is greater than or equal to 2000“MARGINAL” if
CAPE
is greater than or equal to 500“NO RISK” if
CAPE
is less than 500.
You must use an else
and elif
code block. Test the blocks by changing the value of CAPE
.
List the problems in the following markdown cell.
CAPE = 5000
if (CAPE < 2000)
print("SEVERE")
elif (CAPE > 500):
print("MARGINAL
elif (CAPE == 500):
print("NO RISK")
Cell In[16], line 6
print("MARGINAL
^
SyntaxError: unterminated string literal (detected at line 6)
Problems with the following code:
CAPE = 5000
if (CAPE < 2000)
print("SEVERE")
elif (CAPE > 500):
print("MARGINAL
elif (CAPE == 500):
print("NO RISK")
Syntax problems (basic Python errors):
[error description here]
[error description here]
[error description here]
Logic problems (Python does not do what is required):
[logic problem description here]
[logic problem description here]
[logic problem description here]