Python+Fundamentals +Control+Flow+and+Logic
Python+Fundamentals +Control+Flow+and+Logic
Topics Covered
● Comparison operators
● Logical operators
Learning Objectives
● Write simple conditions using comparison operators
So you may be wondering, “How can I take my python to the next level?” That’s exactly what
this section is about. We’re going to bring everything together and start building
impressive programs!
By default, python executes commands from top to bottom, line-by-line, without making
any special decisions beforehand. However, we can change this. With control flow, we can
specify how we want Python to run our code. There’s primarily three forms of control flow:
conditional, looping and branching statements. We don’t need to worry about these for
now, as they will be discussed in detail as we proceed.
Remember the arithmetic operators (+, -, *, /, etc.) and how they helped you process user
input and display a final result? To be able to perform logic (make decisions) with python,
we’ll need to learn a few new operators.
2. Comparison operators
Comparison operators are used to compare values. They always return a boolean value:
True or False. (“yes” or “no”) These, together with logical operators (discussed later), create
boolean expressions that act as the conditions for our decisions.They're essential for
if-statements, loops, assertions, and literally any decision-making in code. Now let’s look
at them one at a time.
2.1. Equal to ( == )
This checks if two values are exactly the same. It’s like asking "Are these twins? Identical
face-to-face?" For example;
● 5 == 5 # True
★ Common Mistakes
○ Using “=” instead of “==” for comparisons
○ “==” is not the same as “is”. “==” compares the values and tells us it’s
true when they match, but “is” compares the objects in memory
directly leading to some unexpected behaviour.
★ Practice question
Compare the output for the following expressions:
○ [1, 2] == [1, 2]
○ [1, 2] is [1, 2]
This checks if values are different. It is essentially the opposite of “==”. For example;
● 10 != 5 # True
● "a" != "b" # True
● 1 != 1 # False
2.3. Greater than ( > )
Is the left value strictly bigger than the right one? For example;
● 10 > 5 # True
● 3 > 7 # False
★ Common Mistakes
○ Using this type of comparison operator with strings the same way as
with integers and floats.
○ This operator works with strings too, but the behaviour is different. With
strings, comparison is done on a letter-by-letter basis (lexicographically).
For example, "banana" > "apple" is True, because ‘b’ > ’a’
Is the left value strictly smaller than the right one? Like checking if you scored less than
your friend on a test. For example;
As you may have guessed, this is the opposite of using the “greater than” comparison
operator (“>”). This works with strings too, with the same behaviour as the “greater than”
operator.
Is the left value either greater or equal to the right? It’s like thinking to yourself, "I’m cool if I
have at least this many points in the final exam." For example;
● 10 >= 10 # True
● 11 >= 10 # True
● 9 >= 10 # False
2.6. Less than or equal to ( <= )
Is the left value less than or equal to the right? It is the opposite to the “greater than or
equal to” above. It’s like thinking to yourself, “Am I under the budget or exactly on it? I can
spend at most this much on snacks today”
Python lets you chain comparisons like math equations: Therefore, an expression such as
5 < x < 10 is the same as 5 < x and x < 10.
This is super useful for range checks; for example when checking whether a person is in a
certain age group, we may use the following code:
age = 20
What we just used is an if-statement which will be discussed in the next topic. Thus you
don’t need to worry about it too much just yet.
● 5 == 5.0 # True
● 4.5 <= 5 # True
Both the above statements are True as comparing values of type int and float is allowed.
However, comparing unrelated types (like int and str) throws an error. For example;
● 5 == "5" # False
● 5 < "5" # TypeError
Example 1 returns False (they are of different types). However, other comparison operators
except “==” will throw a TypeError, as with the second example 2.
Applying the appropriate grade to student scores. In code, this may look like:
grade = "A"
For example in validating eligible applicants to a specific program. This may look
like:
== Equal to a == b
!= Not equal to a != b
if condition:
This is the most basic implementation. The condition may, or may not be, enclosed in
parentheses/round brackets “ () “. This is not necessary for simple conditions, but may be
helpful when conditions get more complex as we’ll discover later.
Now, you may be wondering; “What if I want some code to run when the condition is false?”
That’s where the else-block comes into play. It serves as an extension to the if-statement
allowing us to run code when the condition is false. The syntax is as follows:
if condition:
else:
★ Common Mistakes
○ Failure to indent (add some space to) the next line after the colon
print(“Excellent!”)
print(“Well done!”)
else:
For an 80% grade, Python first checks whether it is greater or equal to 90%, which returns
False. Therefore, it skips the next line and does not print “Excellent!” to the terminal. Next,
it looks at the second condition. Since 80% is less than 90% and greater than 75%, the
condition is True and it prints “Well done!” to the terminal. Once it meets a correct
condition, it ignores the remaining “else” case.
What’s more, you can have as many ‘elif’s as you need! And so you can consider as many
conditions as you like! Also remember that any “elif” cases following the true condition will
also be ignored. Thus the syntax for the if-elif-else extended statement is as follows:
if condition_1:
elif condition_2:
elif condition_3:
else:
In this case, where one condition is dependent (based on) the other, we need a way for one
if-statement (checking if the customer is a student) to be considered when another
if-statement (checking if customer is Ugandan) is True. In Python, this is achieved using
nesting. Nesting is basically putting one statement inside another. In code, this looks
something like this:
if is_Ugandan:
if is_student:
else:
else:
In the example above, is_Ugandan and is_student are variables of the boolean data type
indicating whether the customer is a Ugandan, a student, or neither. The general syntax
for nested if-else statements is as follows:
if condition_1:
if condition_2:
else:
else:
In this example, we are using 4 lines of code just to set the appropriate response. In
reality, there’s a shorter, more efficient way to do this - using the shorthand notation.
With this, we can condense the originally four lines of code into one! While the benefits of
doing it this way are minimal for most cases, the shorthand notation could be useful in
competitive coding and is essential for more advanced concepts such as list
comprehensions. The general syntax is as follows:
★ Common Mistakes
There’s one more skill we need before concluding with if-statements. This will be
particularly helpful when dealing with two or more conditions that need to be considered
before performing a single action. Remember how we could combine comparison
operators to check a range of values? (eg. 18 < age < 25) Logical operators allow us to
combine many conditions to create one result.
When combining two conditions, the and operator returns True if both conditions are True.
If any of the conditions is False, it returns False. With multiple conditions, it only returns
True when all conditions are True. The syntax is as follows:
Example:
age = 25
income = 50000
else:
print("Not eligible")
In this example, both conditions (age > 18 and income > 30000) are True, so the message
"Eligible for loan" is printed. If the age was set to 17, for example, the first condition would
be False and the message “Not eligible” would be printed. Similarly, if the age remained as
25 but the income was reduced below 30000, the second condition would be False and the
message “Not eligible” would be printed. If the age was below 18 and the salary below
30000, both conditions would be False and the message “Not eligible” would be printed as
well.
Truth Table:
When combining two conditions, the or operator returns True if any of the given
conditions is True. or all the conditions are True. It can only be False when all of the
conditions are False, it returns False. The syntax is as follows:
age = 25
income = 50000
else:
print("Not eligible")
For the first case, both conditions (age > 18 and income > 30000) are True, so the message
"Eligible for loan" is printed. If we then set the age to 17, the first condition would be False,
but the second condition would be True, therefore the message “Eligible for loan” would be
printed. Similarly, if the age remained as 25 but the income was reduced below 30000, the
second condition would be False but the first would be True and the message “Eligible for
loan” would be printed.
If the age was below 18 and the salary below 30000, both conditions would be False and
the message “Not eligible” would then be printed.
Truth Table:
This one is a little bit different from the rest of the logical operators. Unlike the other two,
the not operator does not combine multiple conditions but instead reverses the boolean
value of a single condition. If a condition is True, not makes it False. If a condition is False,
not makes it True.
not condition
Example:
is_student = False
if not is_student:
print("Eligible for membership discount")
else:
print("Not eligible")
Explanation:
The variable is_student is False. Applying “not” makes it True, so the message "Eligible for
membership discount" is printed.
Truth Table:
One is not limited to using a single logical operator in their expressions, you can combine
multiple of these operators to form much more complex conditions. For example:
age = 20
is_employed = True
has_bad_credit = False
By this point you may have started wondering, “How can I tell which logical operator is
considered when I combine multiple operators?” “If I have the condition a and b or c, is it
(a and b) or c, or is it a and (b or c)?” This is quite the challenge if you do not understand
how Python approaches chained logical operators.
When combining logical operators, Python evaluates them in the following order:
1. not
2. and
3. or
Example:
x = True
y = False
z = True
Let’s trace the path that Python takes from this expression to the final result. The steps are
in the following order:
From this, we can see that the final result is True. Thus the answer to that earlier question
would be (a and b) or c.
★ Common Mistakes
Range Grade
90-100 A+
80-89 A
70-79 B
60-69 C
50-59 D
<50 F
Bonus: Input validation: Make sure the user enters a score between 0 and 100. If
they enter a score outside that range, print “Invalid score!” to the terminal.
III. Login system: Create a simple login system with the following conditions:
A. Takes in the username and password from the user
B. Compares the input data against hard-coded credentials (username and
password stored under variables)
C. Prints out appropriate messages for each case (eg. “Incorrect password!)