[go: up one dir, main page]

0% found this document useful (0 votes)
11 views68 pages

Chapter2_FlowControl

Uploaded by

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

Chapter2_FlowControl

Uploaded by

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

MODULE-1

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

>>> spam = True


>>> spam
True
>>> true
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined
>>> True = 2 + 2
SyntaxError: can't assign to keyword
COMPARISON OPERATORS

• Comparison operators, also


called relational 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
Example
>>> 42 == 42

>>> 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'

>>> 'hello' == 'Hello'

>>> 'dog' != 'cat'


>>> 42 == 42.0
• The <, >, <=, and >= operators, on the other hand, work properly only with integer and
floating-point values.
• >>> 42 < 100

>>> 42 > 100

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

• The three Boolean operators (and, or,


and not) are used to compare
Boolean values.
• Binary Boolean Operators
• The and operator evaluates an
expression to True if both Boolean
values are True; otherwise, it
evaluates to False.
• >>> True and True
True
>>> True and False
False
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.
• >>> False or True
True
>>> False or False
False
Not operator
• The not operator simply
evaluates to the opposite Boo
• >>> not True
False
>>> not not not not True
Truelean value.
MIXING BOOLEAN AND
COMPARISON OPERATORS

>>> (4 < 5) and (5 < 6)


True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
Exercise
• >>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
4==4and not 4==5 and 4==4
• True and not(False)and(True)
• True and True and True
• True and True
• True
ELEMENTS OF FLOW CONTROL

• Flow control statements often start with a part called


the condition and are always followed by a block of code called
the clause. Before you learn about Python’s specific flow control
statements
ELEMENTS OF FLOW CONTROL

• 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

• Blocks are easier to understand by looking at some indented code, so


let’s find the blocks in part of a small game program, shown here:
• name = 'Mary’
• Password = 'swordfish’
if name == 'Mary’:
print('Hello Mary')
if password == 'swordfish’:
print('Access granted.')
else:
print('Wrong password.')
Program execution

• In the previous chapter’s hello.py program, 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.
flow control Statements

• The statements represent the diamonds you saw in the flowchart in


Figure 2-1, and they are the actual decisions your programs will make.
• if Statements
• if statement could be read as, “If this condition is true, execute the
code in the clause.” 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)
Example
if name == 'Alice’:
print('Hi, Alice.')
• All flow control statements end
with a colon and are followed by
a new block of code (the clause).
This if statement’s clause is the
block with print('Hi, Alice.').
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 always consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)
Example
if name == 'Alice’:
print('Hi, Alice.’)
else:
print('Hello, stranger.')
elif Statements

• 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 con- ditions were False.
• an elif statement always consists of the following:
• The elif 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 elif clause)
Example
if name == 'Alice’:
print('Hi, Alice.’)
elif age < 12:
print('You are not Alice, kiddo.')
Exercise Draw the flowchart for
following code
if name == 'Alice’:
print('Hi, Alice.’)
elif age < 12:
print('You are not Alice, kiddo.’)
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.’)
elif age > 100:
print('You are not Alice, grannie.')
elif Statements

• The order of the elif statements if name == 'Alice’:


does matter, however. Let’s print('Hi, Alice.’)
rearrange them to introduce a
bug. Remember that the rest of elif age < 12:
the elif clauses are automatically print('You are not Alice, kiddo.')
skipped once a True condition elif age > 100:
has been found, print('You are not Alice, grannie.')
• so if you swap around some of elif age > 2000:
the clauses in your program, you print('Unlike you, Alice is not an
run into a problem. undead, immortal vampire.')
Example
if name == 'Alice’:
print('Hi, Alice.’)
elif age < 12:
print('You are not Alice, kiddo.’)
else:
print('You are neither Alice nor a
little kid.')
while Loop Statements

• 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

Execute code below and see the output


name = ‘ '
while name != 'your name’:
print('Please type your name.’)
name = input()
print('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.
Example
Execute the below code and see the output
while True:
print('Please type your name.’)
name = input()
if name == 'your name’:
break
print('Thank you!')
Flow chart
continue Statements

• Like break 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 re-evaluates the loop’s condition.
• (This is also what happens when the execution reaches the end of the
loop.)
Example lets try
while True:
print('Who are you?’)
name = input() #joe
if name != 'Joe’:
continue
print('Hello, Joe. What is the password? (It is a fish.)’)
password = input()
if password == 'swordfish’:
break
print('Access granted.')
Flow Chart
for Loops and the range()
Function
• A for statement looks something like for i in range(3): and includes the
following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Example
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
Output
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
Modified Version Using f-strings (More
Readable)

print('My name is')


for i in range(5):
print(f'Jimmy Five Times ({i})’)

How will you solve using while loop?


How will you solve using while loop
print('My name is’)
i= 0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')’)
i=i+ 1
Flow chart
Lets solve this
• Program Add number from 0 to 100.
total = 0
for num in range(101):
total = total + num
print(total)

Exercise : write above program using while loop


write above program using while
loop
• total = 0
• num = 0 # Start from 0

• while num <= 100:


• total = total + num # Add current number to total
• num = num + 1 # Increment number by 1

• print(total)
n = 100
total = (n * (n + 1)) // 2 # Using integer division
print(total)
The Starting, Stopping, and Stepping
Arguments to range()

for i in range(12, 16): Output


print(i) 12
• The first argument will be where 13
the for loop’s variable starts, and 14
the second argument will be up
to, but not including, the 15
number to stop at.
• 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.
Example
for i in range(0, 10,3):
print(i)

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

• Programs always terminate if the program execution reaches the


bottom of the instructions.
• However, you can cause the program to terminate, or exit, before the
last instruction 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.
Try this program and see what
happens
import sys
while True:
print('Type exit to exit.’)
response = input() #
if response == 'exit’:
sys.exit()
print('You typed ' + response + '.’)
Try this program and see what
happens
• This program has an infinite loop with
no break statement inside.
import sys
• The only way this program will end is
while True:
if the execution reaches the sys.exit()
print('Type exit to exit.’) call.
response = input() # • When response is equal to exit, the
if response == 'exit’: line containing the sys.exit() call is
executed.
sys.exit()
• Since the response variable is set by
print('You typed ' + response + '.’) the input() function, the user must
enter exit in order to stop the
program.
Projects
• A Short Program: Guess the Number
• A Short Program: Rock, Paper, Scissors
• (Refer Code File for code)
• Thank you

You might also like