0% found this document useful (0 votes)
9 views17 pages

Python+Fundamentals +Control+Flow+and+Logic

This document covers control flow and logic in Python, focusing on comparison and logical operators, as well as conditional statements like if-elif-else. It explains how to write conditions, make decisions based on those conditions, and introduces nested if-else statements for more complex decision-making. The document also highlights common mistakes and provides examples for better understanding.

Uploaded by

sanywamaria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views17 pages

Python+Fundamentals +Control+Flow+and+Logic

This document covers control flow and logic in Python, focusing on comparison and logical operators, as well as conditional statements like if-elif-else. It explains how to write conditions, make decisions based on those conditions, and introduces nested if-else statements for more complex decision-making. The document also highlights common mistakes and provides examples for better understanding.

Uploaded by

sanywamaria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Control Flow and Logic

Topics Covered
●​ Comparison operators

●​ Logical operators

●​ Conditional statements ( if-elif-else )

Learning Objectives
●​ Write simple conditions using comparison operators

●​ Apply logical operators to write more complex conditions

●​ Apply if/else logic to make decisions

●​ Apply elif and nested if/else statements to compare multiple conditions


1.​ Introduction to control flow
By now, you can build and run basic python programs that can receive data from the user
and output information. You’ve also learnt the different data types and simple operations
in python.

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!

1.1.​ What is control flow in python?


In our day-to-day life, we ask ourselves a lot of questions. “Is it time to wake up?” “What
shoes should I wear today?” “What should I have for lunch?” For every question we ask, we
make a decision and then take action. Computer programs are no different. Even very
complex systems are a series of questions that help the computer make a decision and
take action.

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.

1.2.​ What is logic in programming?


Whenever we perform an action, we make a decision. A computer can also decide what to do
depending on what it is given. Decision making in computers is actually really easy. It is just a
series of yes/no questions. You’ve actually met this before - the boolean data type. “Yes” is
represented by “True” and “No” is represented by “False”.

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

●​ "cat" == "cat"​ ​ ​ ​ # True

●​ "cat" == "dog"​​ ​ ​ # False

★​ 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]

2.2.​ Not equal to ( != )

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’

2.4.​ Less than ( < )

Is the left value strictly smaller than the right one? Like checking if you scored less than
your friend on a test. For example;

●​ 5 < 10​ ​ ​ ​ ​ # True


●​ 100 < 1​ ​ ​ ​ # False

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.

2.5.​ Greater than or equal to ( >= )

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”

●​ 10 <= 10​ ​ ​ ​ # True


●​ 8 <= 10 ​ ​ ​ ​ # True
●​ 15 <= 10 ​ ​ ​ ​ # False

2.7.​ Bonus: Chained Comparisons

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

if 18 <= age <= 25:

print("You're in the target group!")

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.

2.8.​ Comparing Different Types

Python lets you compare different numeric types; for example:

●​ 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.

2.9.​ Real-Life Use Cases

I.​ Grading logic:

Applying the appropriate grade to student scores. In code, this may look like:

if score >= 90:

​ ​ grade = "A"

II.​ User input validation:

For example in validating eligible applicants to a specific program. This may look
like:

if 18 < age < 25:

​ ​ print("You are eligible for this course.")

Summary: List of comparison operators

Operator Meaning Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b


3.​ Conditional Statements: Making Decisions
It’s finally time to make our computers think! And with that, we’re going to learn some new
and simple syntax. Remember, syntax is simply a way you write your code so that the
computer can understand it. In python, decisions are made using the conditionals we
learnt before, and the if… elif… else… statements.

3.1.​ The if-statement


At its most basic, the if-statement is simple: the word “if” followed by a condition and a
colon ( : ), then the code to run when the condition is true follows, indented, in the next
line. The general syntax is as follows:

if condition:

​ # code to run if condition is true

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:

​ # code to run if condition is true

else:

​ # code to run if condition is false

★​ Common Mistakes

○​ Missing colon after the condition in the if-statement

○​ Failure to indent (add some space to) the next line after the colon

○​ Inconsistent indentation throughout your code. This gives rise to an


IndentationError. It’s good practice to use 4-spaces for indentation in
Python
3.2.​ The “elif” keyword
The “elif” keyword is a kind of composite word obtained by combining the first part of
“else” with “if”. So “else + if” is shortened into “elif.” It is useful when we want to test
multiple conditions before reaching an answer. Consider a teacher adding comments to
their students’ grades. Marks greater than or equal to 90% earn the comment “Excellent!”,
those between 90% and 75% earn the comment “Well done!” and the rest have the
comment “Good, you can do better!” We can implement this in code as follows:

if grade >= 90:

​ print(“Excellent!”)

elif 90 > grade >= 75:

​ print(“Well done!”)

else:

​ print(“Good, you can do better!”)

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:

​ # code to run when the first condition is true

elif condition_2:

​ # code to run when the second condition is true

elif condition_3:

​ # code to run when the third condition is true

else:

​ # code to run when none of the conditions is true


3.3.​ Nested if-else statements
So you can now check multiple conditions and perform an action accordingly. But what if
you have a condition that depends on another? For example if you want to apply a
discount for all Ugandans, but add a bonus item if the customer is also a student? For the
student to get the bonus, they should be Ugandan.

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:

​ print(“I am Ugandan. I got a discount!”)

​ if is_student:

​ ​ print(“I am a Ugandan student, I got the bonus too!”)

​ else:

​ ​ print(“I am Ugandan but not a student. No bonus for me!”)

else:

​ print(“I am not Ugandan, I didn’t get a discount”)

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:

​ # runs if condition 1 is true

​ if condition_2:

​ ​ # runs if condition 1 and condition 2 are both true

​ else:

​ ​ #runs if condition 1 is true but 2 is false

else:

​ # runs if condition 1 is false


Of course, all the earlier rules for the if-elif-else statements apply to the nested
if-statement. And it doesn’t have to stop at one level, you could have an if-statement,
inside an if-statement, inside an if-statement, inside an if-statement… and so on to your
heart’s content. However, it isn’t exactly advised as it makes debugging your code (finding
solutions to errors) more difficult. It is simply another tool to add to your programming
toolbox.

3.4.​ Shorthand if-else statements


When we only need to do a quick check for a simple condition before performing an
action, it is unnecessary to have a large if-block just to get it done. For reference, consider
the following program:

num = int(input(“Enter a number less than 10: “))


if num < 10:
​ response = “Thank you!”
else:
​ response = “Invalid input!”
print(response)

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.

num = int(input(“Enter a number less than 10: “))

response = “Thank you!” if num < 10 else “Invalid input!”


print(response)

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:

action_1 if condition_1 else action_2 if condition_2 else action_3 if condition_3 … else


default_action

★​ Common Mistakes

○​ Forgetting to convert the input to an integer before the comparison

○​ Without it, we would get a TypeError, because we’d be trying to compare


two values of different data types. (input() returns a string)
4.​ Logical operators: The Final Piece
We are so close to our goal of becoming experts in python decision making. We already
know how to check for multiple conditions before making a decision, even when one
condition depends on another. We also know the shorthand syntax for those quick checks
before performing an action.

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.

4.1.​ The “and” operator

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:

condition_1 and condition_2 and condition_3 and …

Example:

age = 25

income = 50000

if age > 18 and income > 30000:

print("Eligible for loan")

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:

Condition 1 Condition 2 Result

True True True

True False False

False True False

False False False

4.2.​ The “or” operator

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:

condition_1 or condition_2 or condition_3 or …

Using the same example as before:

age = 25

income = 50000

if age > 18 or income > 30000:

print("Eligible for loan")

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:

Condition 1 Condition 2 Result

True True True

True False True

False True True

False False False

4.3.​ The “not” operator

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.

Its syntax is as follows:

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:

Condition not Condition Result

True False False

False True True

4.4.​ Combining Logical Operators

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

if age > 18 and is_employed and not has_bad_credit:


print("Loan approved")
else:
print("Loan denied")

For this case, all conditions are favorable: age > 18 is True, is_employed is True, and not
has_bad_credit is True (since has_bad_credit is False). Therefore, the message "Loan
approved" is printed. Try building your own complex boolean expressions (combinations of
comparison and logical operators that return a boolean value) to build a deeper
understanding of the concept!
4.5.​ Operator Precedence

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

result = x or y and not z

Let’s trace the path that Python takes from this expression to the final result. The steps are
in the following order:

1)​ not z → not True → False​

2)​ y and not z → False and False → False​

3)​ x or (result from step 2) → True or False → True

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

○​ Using bitwise operators &, |, ~ instead of logical and, or, not

Summary: Logical operators

Operator Description Example Syntax

and Returns True if both conditions are condition1 and condition2


True

or Returns True if at least one condition1 or condition2


condition is True

not Reverses the boolean value of a not condition


condition

5.​ Wrap it up with a challenge!


I.​ Quick round:

What is the output of the following code?


(Think carefully about operator precedence and the effect of the not keyword!)
age = 17
has_id = True
is_student = False

if not (age >= 18 or is_student and has_id):


print("Access granted")
else:
print("Access denied")
II.​ Grading System: Design a program that:
A.​ Asks the user to input a score
B.​ Prints out a grade based on the following table:

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!)

You might also like