Flow Control in Python
Flow Control in Python
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
• 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.
• 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
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.
10
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.
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
Try this !!
15
Now, let’s explore the most important piece of flow control: the statements
Themselves.
if Statements
16
Start
if name == ‘Dsatm’:
print(‘Hi, Dsatm’)
name == TRUE
print(‘Hi, Dsatm’)
‘Dsatm’
FALSE
Try this !!
End
17
18
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 !!
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
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.
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:
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.
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.
36
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 :
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 :
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.
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.
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 ??
46
47
from import Statements
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.
50
51
A Short Program: Rock, Paper, Scissors
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