Chapter2_FlowControl
Chapter2_FlowControl
CH 2
FLOW CONTROL
Introduction
• Program is just a series of instructions. But programming’s real
strength isn’t just running one instruction after another like a
weekend errand list.
• Based on how expressions evaluate, a program can decide to skip
instructions, repeat them, or choose one of several instructions to
run. In fact, you almost never want your programs to start from the
first line of code and simply execute every line, straight to the
end. Flow control statements can decide which Python instructions to
execute under which conditions.
Introduction
Introduction
• Before you learn about flow control statements, you first need to
learn how to represent those yes and no options, and you need to
understand how to write those branching points as Python code. To
that end, let’s explore Boolean values, comparison operators, and
Boolean operators.
BOOLEAN VALUES
• Boolean data type has only two values: True and False. (Boolean is
capitalized because the data type is named after mathematician
George Boole.)
• 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.
BOOLEAN VALUES
>>> 42 == 99
>>> 2 != 3
>>> 2 != 2
Example
>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False
• Note that an integer or floating-point value will always be unequal to
a string value.
>>> 42 == '42'
False
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> 42 == 42.0
True
• Note that an integer or floating-point value will always be unequal to
a string value.
>>> 42 == '42'
>>> 42 < 42
>>> eggCount = 42
>>> eggCount <= 42
>>> myAge = 29
>>> myAge >= 10
• The <, >, <=, and >= operators, on the other hand, work properly only with integer and
floating-point values.
• >>> 42 < 100
True
>>> 42 > 100
False
>>> 42 < 42
False
>>> eggCount = 42
>>> eggCount <= 42
True
>>> myAge = 29
>>> myAge >= 10
True
• THE DIFFERENCE BETWEEN THE == AND = OPERATORS
• The == operator (equal to) asks whether two values are the same as each
other.
• 2==2
• The = operator (assignment) puts the value on the right into the variable on
the left.
• A=2
BOOLEAN OPERATORS
• Conditions
• The Boolean expressions you’ve seen so far could all be considered
conditions , which are the same thing as expressions; condition is just
a more specific name in the context of flow control statements.
• 4<6
• True
ELEMENTS OF FLOW CONTROL
• Blocks of Code
• Lines of Python code can be grouped together in blocks.
• There are three rules for blocks.
• Blocks begin when the indentation increases.
• Blocks can contain other blocks.
• Blocks end when the indentation decreases to zero or to a containing block’s
indentation.
Blocks of Code
• You can make a block of code execute over and over again using a
while statement.
• while statement always consists of the following:
• The while 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 while clause)
Difference between while loop and if
clause
• 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.
Difference between while loop and if
clause
spam = 0 spam = 0
if spam < 5: while spam < 5:
print('Hello, world.’) print('Hello, world.’)
spam = spam + 1
spam = spam + 1
• o/p :
• o/p : Hello, world.
Hello, world. Hello, world.
Hello, world.
Hello, world.
Hello, world.
Difference
An Annoying while Loop
• print(total)
n = 100
total = (n * (n + 1)) // 2 # Using integer division
print(total)
The Starting, Stopping, and Stepping
Arguments to range()
0,1,2,3,4,5,6,7,8,9
O/P : 0,3,6,9
• So calling range(0, 10, 2) will count from zero to eight by intervals of two.
• 0,1,2,3,4,5,6,7,8,9
• O/p : 0,2,4,6,8
• output
0
2
4
6
8
Example
• The range() function is flexible in the sequence of numbers it produces for for
loops.
• For example : you can even use a negative number for the step argument to
make the for loop count down instead of up.
for i in range(5, -1, -1):
print(i)
O/P
5
4
3
2
1
0
Importing Modules
• All Python programs can call a basic set of functions called built-in
functions,
• E.g print(), input(), and len() functions
• Python also 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
• math module has mathematics- related functions,
• random module has random number-related functions,
Importing Modules
• you must import the module with an import statement. Before you
use functions in module
• an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
• Import random ,math
• Once you import a module, you can use all the cool functions of that
module
random – Provides functions for generating random numbers.
•Example: random.randint(1, 10) → Generates a
random integer
• between 1 and 10.
sys – Provides system-related functions and allows interaction with
the interpreter.
•Example: sys.exit() → Exits the program.
os – Provides functions for interacting with the operating system.
•Example: os.getcwd() → Returns the current working
directory.
math – Provides mathematical functions and constants.
•Example: math.sqrt(25) → Returns the square root of 25
(which is 5).
Example
import random #importing Output
module 4
for i in range(5): 1
print(random.randint(1, 10)) 8
4
1
Example
• Here’s an example of an import statement that imports four different
modules:
• import random, sys, os, math
• Now we can use any of the functions in these four modules.
• Another way to import module
• from import Statements
• from random import *
Example:
• import imports the whole library.
• from import imports a specific
member or members of the library. Use from import when you want to save
yourself from typing the module name over
• Import example: and over again.
In other words, when referring to a member of
import datetime the module many times in the code.
d1 = datetime.date(2021, 10, 19) Use import when you want to use multiple
members of the module.
• from Example:
from datetime import date
d1 = date(2021, 10, 19)
Ending a Program Early with the sys.exit()
Function