Conditional statements are used to check conditions and provide appropriate responses. You can think of this as asking a question; receiving an answer; then performing an action in response to the answer. For example:
Question: Is the ball red?
Action: Place it in the bucket labelled “red balls”.
To explore Python’s various conditional statements, create a new sketch and save it as “conditional_statements”. Add the following code:
At this point, you are familiar with three datatypes: string, integer, and float. Before moving onto conditional statements, you require an introduction to a fourth type: boolean.
A boolean can represent one of two possible states:
False. Note that when writing these values, the first letter is always uppercase and no quotation marks are used (as this would make the value a string). Add the following code:
Relational operators determine the relationship between two operands. Consider this basic example:
3 > 2
In this case,
2 are the operands. The
> sign is the operator. Three is greater than two, so this statement is true. To see how this works in Python, add the following code to your “conditional_statements” sketch:
Take note of how the relational operations return a boolean value; this will be important in the next section. Here’s a list of Python’s various relational operators:
!= operators have the ability to operate on both numbers and strings:
Relational operators are particularly useful when combined with
if and other conditional statements.
If statements are one of the essential means of introducing logic to your program. Add this basic example to your working sketch:
The code awards a PASS grade for any mark greater-than-or-equal-to fifty. In the above case the
mark >= 50 returns
True; so the
print('PASS') line is executed. It’s vital that you indent the
if line is executed upon the condition returning
True. For example, the following code will print “PASS” and “Well done!” for any mark greater-than-or-equal-to fifty:
But, the following code will print “Well done!” regardless of whether or not the mark exceeds fifty:
To nest an
if statement within another
if statement, increase the indentation accordingly:
The above displays “Bien Hecho!”.
If you are evaluating a boolean value you may leave out the
== operator. For example:
ball_is_green variable is equal to
True, so typing
ball_is_green == True is equivalent to
True == True. Either way, the answer is
True! Still, if you find it helps to be more explicit, you can use the first version.
Currently, the grading program can only award a PASS. Ideally, it should assign letter grades (A/B/C/…). This requires additional if statements. Adapt your code:
As you’d expect, the console displays a “C”. But there’s an issue – a mark of
70 results in a “C” and “B”:
The problem here’s that both
if statements operate independently of one another. If the grade is awarded a “B” then there’s no need to check the C condition. An
elif (else-if) statement is required, along with some reordering of your code:
This correctly displays a “B” in the Console. Because the
if line returns
elif is skipped. This is why the correct ordering of
elif statements is vital; should the C condition to come first, every mark greater-than-or-equal-to 50 is awarded a C-grade, as the B condition is skipped.
elif statement to the code, adjusting the mark to test three different cases:
To visually group the connected
elif statements, the empty line between each has been removed; this is a matter of style, but you are welcome to add as many blank lines as you see fit. You may add as many additional
elif statements as you need.
A mark below
50 passes through all of the
elif statements without invoking any action. To handle FAIL cases, one can employ the
Else statements handle any condition that does not match that specified in the
if statement (or
elif grouping). Add an
else statement to your code:
else statement need not necessarily follow an
elif. For example:
Of course, this all depends on the logic you intend to implement.
Thus far, each of the
elif statements have been based on the outcome of a single relational operation; for instance:
is the mark greater-than-or-equal-to fifty?
However, there are many occasions where multiple relational operations must be evaluated within a single condition; for example:
is the mark greater-than-or-equal-to forty-five AND less-than fifty?
For these purposes, Python provides three logical operators:
True if both operands are true
True if at least one operand is true
not reverses the boolean (
False and vice-versa)
and condition to handle marks in the RESUBMIT range:
Now add an
or condition to catch marks outside of the valid range:
not operator has its uses but is awkward to apply in the working example. Instead, here’s a one-line example of it in action:
print( not False ) # displays: True
In this challenge, you’ll apply conditional statements to a visual task. Create a new sketch and save it as “four_square”. Add the following code:
The above code divides the display window into four quadrants:
Next, place a character at some location determined by an x- and y-coordinate variable:
Your challenge is to write conditional statements to replace the
? character with an
O to match the colour beneath it. This way, one can adjust just the
y values and the character changes accordingly:
To start you off, here’s the code for the red (
However, if you change the
y value to
400, an “R” is displayed over the orange quadrant. Begin by correcting this, then address the other quadrants.