Module 1.2
Module 1.2
Flow control: Boolean Values, Comparison Operators, Boolean Operators, Mixing Boolean and
Comparison Operators, Elements of Flow Control, Program Execution, Flow Control Statements,
Importing Modules
Boolean Values
The Boolean data type has only two values: True and False. When typed as Python code, the
Boolean values True and False lack the quotes you place around strings, and they always start with
a capital T or F, with the rest of the word in lowercase.
1. Boolean values are used in expressions and can be stored in variables
Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean value.
These operators evaluate to True or False depending on the values you give them.
As you might expect, == (equal to) evaluates to True when the values on both sides are the same,
and != (not equal to) evaluates to True when the two values are different.
The == and != operators can actually work with values of any data type.
The <, >, <=, and >= operators, on the other hand, work properly only with integer and floating-
point values.
Boolean Operators
The three Boolean operators (and, or, and not) are used to compare Boolean values. Like
comparison operators, they evaluate these expressions down to a Boolean value.
Binary Boolean Operators
The and and or operators always take two Boolean values (or expressions), so they’re considered
binary operators.
1. and Operator
The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
Truth Table
2. or Operator
The or operator evaluates an expression to True if either of the two Boolean values is True.
If both are False, it evaluates to False.
Truth Table
Truth Table
Mixing Boolean and Comparison Operators
The computer will evaluate the left expression first, and then it will evaluate the right expression.
When it knows the Boolean value for each, it will then evaluate the whole expression down to one
Boolean value. You can also use multiple Boolean operators in an expression, along with the
comparison operators.
Flow control statements often start with a part called the condition, and all are followed by a block
of code called the clause.
Conditions:
The Boolean expressions could all be considered conditions, which are the same thing as
expressions; Conditions always evaluate down to a Boolean value, True or False. A flow control
statement decides what to do based on whether its condition is True or False, and almost every
flow control statement uses a condition.
Blocks of Code:
Lines of Python code can be grouped together in blocks. When a block begins and ends from the
indentation of the lines of code. There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.
Program Execution
Python started executing instructions at the top of the program going down, one after another. The
program execution (or simply, execution) is a term for the current instruction being executed
if Statements
The most common type of flow control statement is the if statement. An if statement’s clause will
execute if the statement’s condition is True. The clause is skipped if the condition is False.
In Python, an if statement consists of the following:
● The if keyword
● A condition (that is, an expression that evaluates to True or False)
● A colon
● Starting on the next line, an indented block of code (called the if clause)
For example, let’s say you have some code that checks to see whether someone’s name is Alice.
All flow control statements end with a colon and are followed by a new block of code (the clause).
Below figure shows what a flowchart of this code would look like.
else Statements
An if clause can optionally be followed by an else statement. The else clause is executed only
when the if statement’s condition is False. An else statement doesn’t have a condition, and in
code, an else statement always consists of the following:
Eg:
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
elif Statements
While only one of the if or else clauses will execute, you may have a case where you want one of
many possible clauses to execute. The elif statement is an “else if” statement that always follows
an if or another elif statement. It provides another condition that is checked only if any of the
previous conditions were False. In code, an elif statement always consists of the following:
This time, you check the person’s age, and the program will tell them something different if
they’re younger than 12.
Optionally, you can have an else statement after the last elif statement. In that case, it is guaranteed
that at least one (and only one) of the clauses will be executed. If the conditions in every if and elif
statement are False, then the else clause is executed. For example
while Loop Statements
The code in a while clause will be executed as long as the while statement’s condition is True. In
code, a while statement always consists of the following:
You can see that a while statement looks similar to an if statement. The difference is in how they
behave. At the end of an if clause, the program execution continues after the if statement. But at
the end of a while clause, the program execution jumps back to the start of the while statement.
The while clause is often called the while loop or just the loop.
Eg:
Output
Please type your name.
Al
Please type your name.
Albert
Please type your name.
%#@#%*(^&!!!
Please type your name.
your name
Thank you!
break Statements
There is a shortcut to getting the program execution to break out of a while loop’s clause early. If
the execution reaches a break statement, it immediately exits the while loop’s clause. In code, a
break statement simply contains the break keyword.
The first line creates an infinite loop; it is a while loop whose condition is always True. The
program execution will always enter the loop and will exit it only when a break statement is
executed.
Just like before, this program asks the user to type your name. Now, however, while the execution
is still inside the while loop, an if statement gets executed to check whether name is equal to your
name. If this condition is True, the break statement is run, and the execution moves out of the loop
to print('Thank you!'). Otherwise, the if statement’s clause with the break statement is skipped,
which puts the execution at the end of the while loop. At this point, the program execution jumps
back to the start of the while statement to recheck the condition.
continue Statements
continue statements are used inside loops. When the program execution reaches a continue
statement, the program execution immediately jumps back to the start of the loop and reevaluates
the loop’s condition.
If the user enters any name besides Joe, the continue statement causes the program execution to
jump back to the start of the loop. When it reevaluates the condition, the execution will always
enter the loop, since the condition is simply the value True. Once they make it past that if
statement, the user is asked for a password. If the password entered is swordfish, then the break
statement is run, and the execution jumps out of the while loop to print Access granted. Otherwise,
the execution continues to the end of the while loop, where it then jumps back to the start of the
loop.
for Loops and the range() Function
If you want to execute a block of code only a certain number of times you can do this with a for
loop statement and the range() function.
In code, a for statement looks something like for i in range(5): and always includes the following:
The print() call in the clause will print Jimmy Five Times (0). After Python finishes an iteration
through all the code inside the for loop’s clause, the execution goes back to the top of the loop, and
the for statement increments i by one. This is why range(5) results in five iterations through the
clause, with i being set to 0, then 1, then 2, then 3, and then 4. The variable i will go up to, but will
Some functions can be called with multiple arguments separated by a comma, and range() is one of
them. This lets you change the integer passed to range() to follow any sequence of integers,
including starting at a number other than zero.
The range() function can also be called with three arguments. The first two arguments will be the
start and stop values, and the third will be the step argument. The step is the amount that the
variable is increased by after each iteration.
So calling range(0, 10, 2) will count from zero to eight by intervals of two.
0
2
4
6
8
The range() function is flexible in the sequence of numbers it produces for for loops. For example
(I never apologize for my puns), you can even use a negative number for the step argument to
make the for loop count down instead of up.
Running a for loop to print i with range(5, -1, -1) should print from five down to zero.
5
4
3
2
1
0
Importing Modules
Python comes with a set of modules called the standard library. Each module is a Python program
that contains a related group of functions that can be embedded in your programs.
For example, the math module has mathematics related functions, the random module has random
number–related functions, and so on.
Before you can use the functions in a module, you must import the module with an import
statement. In code, an import statement consists of the following:
Once you import a module, you can use all the cool functions of that module. Let’s give it a try
with the random module, which will give us access to the random.ranint() function.
import random
for i in range(5):
print(random.randint(1, 10))
When you run this program, the output will look something like this:
4
1
8
4
1
The random.randint() function call evaluates to a random integer value between the two integers
that you pass it. Since randint() is in the random module, you must first type random. in front of
the function name to tell Python to look for this function inside the random module.
An alternative form of the import statement is composed of the from keyword, followed by the
module name, the import keyword, and a star; for example,
from random import *.
With this form of import statement, calls to functions in random will not need the random. prefix.
However, using the full name makes for more readable code, so it is better to use the normal form
of the import statement.
The last flow control concept to cover is how to terminate the program. This always happens if the
program execution reaches the bottom of the instructions. However, you can cause the program to
terminate, or exit, by calling the sys.exit() function. Since this function is in the sys module, you
have to import sys before your program can use it.
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
This program has an infinite loop with no break statement inside. The only way this program will
end is if the user enters exit, causing sys.exit() to be called. When response is equal to exit, the
program ends. Since the response variable is set by the input() function, the user must enter exit in
order to stop the program.