My Curiosity |Computers |2|Understanding Control Flow in Programming

When we can take decision, it is that very moment we feel Empowered….

….Yash

1. Introduction to Control Flow

When you wake-up on cold Saturday morning, you may ask yourself, “It’s a Saturday morning, and its cold as well is it the correct time to leave bed, can’t sleep an hour more?”

These questions and decisions control the flow of your morning, each step and result is a product of the conditions and decisions you take on those conditions.

Your computer. just like you, goes through a similar flow every time it executes code. A program will run and start moving through its checklists, is this condition met, is that condition met, okay let’s execute this code and return that value.

This is the control flow of your program. In Python, your script will execute from the top down, until there is nothing left to run. It is your job to include gateways, AKA conditional statements, to tell the computer when it should execute certain blocks of code. If these conditions are met, then run this function.

2. Boolean Expressions

In order to build control flow into our program, we want to be able to check if something is true or not. A Boolean expression is a statement that can be either True or False.

For example, consider this statement, “Would you like to take tea?”, the reply is plain “Yes”, or “No”. In terms of programming language, it is said “True”(yes) or “False”(no).

Now consider this statement, “Getting up early in the morning is a good thing.”, now this statement cannot judge plainly True or False. For some people have different perspectives over it, and we cannot consider it a Boolean statement.

3. Relational Operators: Equals and Not Equals

We can create a Boolean expression by using relational operators. Relational operators compare two items and return either True or False. FOr this reason, you will sometimes hear them called comparators.

The two relational operators we’ll cover first are:

a) Equals: ==

b) Not equals: !=

These operators compare two items and return True or False, if they are equal or not.

i) (5 * 2) – 1 == 8 + 1 => True

ii) 13 – 6 != (3 * 2) + 1 => False

4. Boolean Variables

These Boolean values True and False, they are only two values that are bool type. If you want to assign a variable a bool value, you can choose either of True or False value depending upon your use.

e.g: bool_1 = True | bool_2 = False

You can also set a variable value equal to Boolean expression. When the expression gets resolved, the variable will get assigned to resultant bool value. e.g.: var_1 = 5 != 7 => when the expression gets resolved, variable var_1 will get value as True, since 5 is actually not equal to 7.

“””

bool_one = 5 != 7
bool_two = 1 + 1 != 2
bool_three = 3 * 3 == 9

my_baby_bool = “true”

print(type(my_baby_bool))

my_baby_bool_two = True

print(type(my_baby_bool_two))

#

<class ‘str’>

<class ‘bool’>

#

“””

5. If Statement

Understanding boolean variables and expressions is essential because they are the building blocks of conditional statements. In the waking-up example, the decision making statement, “its weekend, so I will sleep more”, is a conditional statement.

If its a weekend, I will sleep more.

The boolean expression here is, if its a weekend, very easy to answer in yes or no.

If it is weekend == True => I will sleep more.

In Python it will appear like this:

“””

if is_weekend:

print(“I will sleep more”)

6. Relational Operators II

Apart from telling computer to check equals to (==) and not equals to (!=) condition, there are other operators as well.

a) > greater than

b) >= greater than or equal to

c) < less than

d) <= less than or equal to

“””

#Sample Program

x = 20

y = 20

# Write the first if statement here:

if x == y:

  print(“These numbers are the same”)

credits = 120

# Write the second if statement here:

if credits >= 120:

  print(“You have enough credits to graduate!”)

“””

7. Boolean Operators: and

Like in normal day-to-day life, the conditions you want to check in your conditional statement will require more than one Boolean expression to cover. In those cases, you can build larger boolean expressions using boolean operators. These operators (also known as logical operators) combine smaller Boolean expressions into larger Boolean expressions.

There are three Boolean operators that will be covered here:

  • and
  • or
  • not

Let’s discuss and operator first:

and combines two Boolean expressions and evaluates as True if both of its components are True, but False otherwise.

Example code snippet:

“””

(1 + 1 == 2) and (2 + 2 == 4)   # True

(1 > 9) and (5 != 6)            # False

(1 + 1 == 2) and (2 < 1)        # False

(0 == 10) and (1 + 1 == 1)      # False

“””

8. Boolean Operators: or

On the contrary to and operator which checks it’s both component truthiness, or only needs to check one of its statements to be true in order to declare entire condition as true.

Example code snippet:

“””

True or (3 + 4 == 7)    # True
(1 – 1 == 0) or False   # True
(2 < 0) or True         # True
(3 == 8) or (3 > 4)     # False

“””

9. Boolean Operators: not

When applied to any Boolean expression it reverses the Boolean value. It makes a true statement false and vice versa.

Example:

“””

not 1 + 1 == 2 # False
not 7 < 0       # True

“””

“””

#Example program to check whether a student graduated or not

credits = 120

gpa = 1.8

if not credits >= 120:

  print(“You do not have enough credits to graduate.”)

if not gpa >= 2.0:

  print(“Your GPA is not high enough to graduate.”)

if not credits >= 120 and not gpa >= 2.0:

  print(“You do not meet either requirement to graduate!”)

“””

10. Else Statements

else statements allow us to elegantly describe what we want our code to do when certain conditions are not met. You don’t need to use too many if conditions.

“””

if weekday:
  print(“wake up at 6:30”)
else:
  print(“sleep in”)

“””

11. Else If Statements

Apart from if and else statements, we can also have elif statements. An elif statement aka else if statement check another condition after the previous if statements condition aren’t met. We can use elif statements to control the order we want our program to check each of our conditional statements.

“””

print(“Thank you for the donation!”)

if donation >= 1000:
  print(“You’ve achieved platinum status”)
elif donation >= 500:
  print(“You’ve achieved gold donor status”)
elif donation >= 100:
  print(“You’ve achieved silver donor status”)
else:
  print(“You’ve achieved bronze donor status”)

“””

Story of computer , , , , , , , , ,

Discover more from Logic Searcher

Subscribe now to keep reading and get access to the full archive.

Continue reading