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

Flow Control in Python

Uploaded by

sushma-icb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
9 views56 pages

Flow Control in Python

Uploaded by

sushma-icb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 56

1.

TOPICS

1. 1. FLOW CONTROL
2. 2. BOOLEAN VALUES
3. 3. COMPARISON OPERATORS
4. 4. BOOLEAN OPERATORS
5. 5. MIXING BOOLEAN AND COMPARISON
OPERATORS
6. 6. ELEMENTS OF FLOW CONTROL
7. 7. PROGRAM EXECUTION
8. 8. FLOW CONTROL STATEMENTS
9. 9. IMPORTING MODULES
1
10. 10. ENDING A PROGRAM EARLY WITH SYS.EXIT()
Department of CSE, DSATM
11. PRACTICE QUESTIONS !!
1. FLOW CONTROL
Flow control statements can decide which Python instructions to execute under which conditions.
Example :

Flowcharts representations :
• Branching points – diamonds
• Steps – rectangles
• Starting and Ending steps -
rounded rectangles

Department of CSE, DSATM


1. 2. BOOLEAN VALUES

• The Boolean data type has only two values: True and False.
• Boolean is capitalized because the data type is named after mathematician
George Boole.
• When entered 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.

Department of CSE, DSATM


So let’s Try this !!

• Like any other value, Boolean values are used in expressions and can be stored in variables
1. If you don’t use the proper case
2. or you try to use True and False for variable names
3. Python will give you an error message

4
1. 3. 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. 5

Department of CSE, DSATM


So let’s Try this !!

The == and != operators can actually work with values of any data type.

6
Try this !!
Note :
• An integer or floating-point value
will always be unequal to a string
value.
• The expression 42 == '42' 
evaluates to False because Python
considers the integer 42 to be
different from the string '42'.

7
Try this !!

8
9
1. 4. 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.
• The AND operator evaluates an expression to True if both Boolean values are True; otherwise, it
evaluates to False.

10

Department of CSE, DSATM


The not Operator
Unlike and and or, the not operator operates on only one Boolean value (or expression). This
makes it a unary operator. The not operator simply evaluates to the opposite Boolean value.

Mixing Boolean and Comparison Operators

Since the comparison operators evaluate to Boolean values, you can use them in expressions with the
Boolean operators.

11
Try this !!

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.
12
1. 5. MIXING BOOLEAN AND COMPARISON OPERATORS

Try this !!

The Boolean operators have an order of operations just like the math operators do.
After any math and comparison operators evaluate, Python evaluates the not
operators first, then the and operators, and then the or operators.

13
1. 6. 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.

a. Conditions – Boolean Expressions evaluating to true or false.


• 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.
• Conditions always evaluate down to a Boolean value, True or False.

b. Blocks of code
• Lines of Python code can be grouped together in blocks.
• You can tell when a block begins and ends from the indentation of the lines of code.
• 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.

14

Department of CSE, DSATM


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:

Try this !!

15

Department of CSE, DSATM


1. 7. FLOW CONTROL STATEMENTS

Now, let’s explore the most important piece of flow control: the statements
Themselves.
if Statements

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)

16

Department of CSE, DSATM


1. 7. FLOW CONTROL STATEMENTS

Start

if name == ‘Dsatm’:
print(‘Hi, Dsatm’)
name == TRUE
print(‘Hi, Dsatm’)
‘Dsatm’

FALSE

Try this !!

End

17

Department of CSE, DSATM


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)

18

Department of CSE, DSATM


if name == ‘Dsatm’: Start
print(‘Hi, Dsatm’)
else
print(‘Hi, Stranger’)
FALSE TRUE
print(‘Hi, Stranger’) name == ‘Arun’ print(‘Hi, Arun’)

End

Try this !! 19
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 all of the previous
conditions were False.

20
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')

Try this !!

21
Try this !!

22
The order of the elif statements does matter, however. Let’s rearrange them to introduce a bug !!

Try this !! What is the output ??


23

Department of CSE, DSATM


The order of the elif statements does matter, however. Let’s rearrange them to introduce a bug !!

The string 'You are not Alice, grannie.' is printed, and the rest of the elif statements are automatically skipped.
Remember that at most only one of the clauses will be executed, and for elif statements, the order matters!

24

Department of CSE, DSATM


Analyze !! What is the output ??

The X path will logically never happen, because if


age were greater than 2000, it would have already
been greater than 100.

25
We 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.

Try this !! What is the output ??


26
In plain English, this type of flow control
structure would be “If the first condition is
true, do this. Else, if the second condition
is true, do that.
Otherwise, do something else.” When you
use if, elif, and else statements together,
remember these rules about how to order
them to avoid bugs like the one in
previous flowchart !!

27
PROGRAM-1
a. Develop a program to read the student details like Name,
USN, and Marks in three subjects. Display the student
details, total marks and percentage with suitable messages.

28
PROGRAM-1
b. Develop a program to read the name and year of birth of a
person. Display whether the person is a senior citizen or not.

29
Loop Statements

30
while Loop Statements:

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

Syntax:
while expression:
statement(s)

31
32
Try this !! What is the output ??

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

Try this !! What is the output ??


Flowchart next slide

34
Try this !! What is the output ??

35
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 reevaluates the loop’s condition.

Try this !! What is the output ??


Flowchart next slide

36

Department of CSE, DSATM


If the user enters any name besides Joe (1),
the continue statement (2) causes the program execution to
jump back to the start of the loop. When the program
reevaluates the condition, the execution will always enter the
loop, since the condition is simply the value True. Once the user
makes it past that if statement, they are asked for a
password(3), If the password entered is swordfish, then the
Output :
break statement (4) is run, and the execution jumps out of the
while loop to print Access granted (5) Otherwise, the execution
continues to the end of the while loop, where it then jumps back
to the start of the loop.

37
If the user enters any name besides Joe (1),
the continue statement (2) causes the program execution to
jump back to the start of the loop. When the program
reevaluates the condition, the execution will always enter the
loop, since the condition is simply the value True. Once the user
makes it past that if statement, they are asked for a
password(3), If the password entered is swordfish, then the
break statement (4) is run, and the execution jumps out of the
while loop to print Access granted (5) Otherwise, the execution
continues to the end of the while loop, where it then jumps back
to the start of the loop.

38
for Loops and the range() Function
A for statement looks something like for i in range(5): 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)

Syntax:
for iterator_var in sequence:
statements(s)

39
Try this !! What is the output ??

Output :

Rewrite the above with a While Loop Now !! 40


An Equivalent while Loop :

Output :

41
The Starting, Stopping, and Stepping Arguments to range() :

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.

Output :

Try this !! What is the output ??

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

Try this !! What is the output ??

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

Try this !! What is the output ??

44
1. 9. IMPORTING MODULES
• All Python programs can call a basic set of functions called built-in functions, including the 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.
• Examples: Math Module, Random Module
• 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:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas

45
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.randint() function.
Try this !! What is the output ??

example of an import statement that imports four different modules:

46
47
from import Statements

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 import random form of the statement.

48
1. 10. ENDING A PROGRAM EARLY WITH SYS.EXIT()

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.

Run this program in IDLE. This program has an infinite


loop with no break statement inside. The only way this
program will end is if the execution reaches the sys.exit()
call. When response is equal to exit, the line containing
the sys.exit() call is executed. Since the response variable
is set by the input() function, the user must enter exit in
order to stop the program.
49
A Short Program: Guess the Number
The examples I’ve shown you so far are useful for introducing basic concepts, but
now let’s see how everything you’ve learned comes together in a more complete
program. In this section, I’ll show you a simple “guess the number” game. When you
run this program, the output will look something like this:

50
51
A Short Program: Rock, Paper, Scissors

Let’s use the programming concepts we’ve learned so far to


create a simple rock, paper, scissors game. The output will
look like this:

52
53
1. 11. PRACTICE QUESTIONS

1. What do the following expressions evaluate to? 2. Identify the three blocks in this code:
(5 > 4) and (3 == 5)
not (5 > 4)
(5 > 4) or (3 == 5)
not ((5 > 4) or (3 == 5))
(True and True) and (True == False)
(not False) or (not True)

54
1. PRACTICE QUESTIONS

3. Write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints
Greetings! if anything else is stored in spam.
4. What is the difference between range(10), range(0, 10), and range(0, 10, 1) in a for loop?
5. Write a short program that prints the numbers 1 to 10 using a for loop. Then write an equivalent
program that prints the numbers 1 to 10 using a while loop.
6. Look up the round() and abs() functions on the internet, and find out what they do. Experiment with
them in the interactive shell.

55
THANK
YOU

Department of CSE, DSATM Acknowledgement : Al Sweigart

You might also like