0% found this document useful (0 votes)
28 views38 pages

Unit - II

The document discusses decision control statements in Python, including if statements, if-else statements, nested if statements, and if-elif ladders, which are used to control the flow of program execution based on conditions. It also covers logical operators like 'and' and 'or', as well as loop constructs such as for and while loops, including their break and continue statements. Additionally, the document explains the use of the pass statement as a placeholder in Python code.

Uploaded by

sushma.chavan
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)
28 views38 pages

Unit - II

The document discusses decision control statements in Python, including if statements, if-else statements, nested if statements, and if-elif ladders, which are used to control the flow of program execution based on conditions. It also covers logical operators like 'and' and 'or', as well as loop constructs such as for and while loops, including their break and continue statements. Additionally, the document explains the use of the pass statement as a placeholder in Python code.

Uploaded by

sushma.chavan
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

Unit II

Decision Control Statements


Decision Control Statements

There comes situations in real life when we need to make some decisions and based
on these decisions, we decide what should we do next. Similar situations arises in programming also
where we need to make some decisions and based on these decision we will execute the next block of
code.

Decision making statements in programming languages decides the direction of flow of program execution.
Decision making statements available in python are:


if statement

if..else statements

nested if statements

if-elif ladder
if statement

if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.

Syntax:
 if condition:
 # Statements to execute if
 # condition is true


Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the
value is true then it will execute the block of statements below it otherwise not. We can use condition
with bracket ‘(‘ ‘)’ also.


As we know, python uses indentation to identify a block. So the block under an if statement will be identified as
shown in the below example:

 if condition:
 statement1
 statement2


# Here if the condition is true, if block

# will consider only statement1 to be inside

# its block.
Flow chart

Python Conditions and If
statements

Python supports the usual logical conditions from mathematics:

Equals: a == b

Not Equals: a != b

Less than: a < b

Less than or equal to: a <= b

Greater than: a > b

Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.


Example

If statement:

a = 33

b = 200

if b > a:

print("b is greater than a")

Indentation

Python relies on indentation (whitespace at the beginning
of a line) to define scope in the code. Other programming
languages often use curly-brackets for this purpose.


Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

nested-if


A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows
us to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.


Syntax:

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart for nested if
# python program to illustrate nested If statement

i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too

if- else

The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it won’t.
But what if we want to do something else if the condition is false.
Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is
false.

Syntax:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow chart for if-else
Program for if-else :to check greatest number
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

if-elif-else ladder

Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.


Syntax:-

if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flowchart

Python program to illustrate if-elif-else ladder

i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")

Output:

i is 20

And

The and keyword is a logical operator, and is used to combine
conditional statements:


Example
 Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine
conditional statements:


Example
 Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
For loop

The for loop in Python is used to iterate over a sequence (list,
tuple, string) or other iterable objects. Iterating over a sequence
is called traversal.


Syntax of for Loop
for val in sequence:
Body of for

Here, val is the variable that takes the value of the item inside the
sequence on each iteration.


Loop continues until we reach the last item in the sequence. The
body of for loop is separated from the rest of the code using
indentation.
Flowchart
Example
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

# Output: The sum is 48


print("The sum is", sum)

Output :
The sum is 48

The range() function

We can generate a sequence of numbers using
range() function. range(10) will generate numbers
from 0 to 9 (10 numbers).

We can also define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if
not provided.

This function does not store all the values in memory,
it would be inefficient. So it remembers the start, stop,
step size and generates the next number on the go.

To force this function to output all the items, we can
use the function list().

The following example will clarify
this.

# Output: range(0, 10)


print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

For with The break Statement

With the break statement we can stop the loop before it has looped through all the items:


Example

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
Break
Output :apple
banana


Example

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
Output :
Apple

For with The continue Statement

With the continue statement we can stop the current
iteration of the loop, and continue with the next:

Example

Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)
Output :apple
cherry

for loop with else

A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.

break statement can be used to stop a for loop. In such case, the
else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

Output :
0
1
5
No items left.
While loop

The while loop in Python is used to iterate over a block of code as long
as the test expression (condition) is true.

We generally use this loop when we don't know beforehand, the
number of times to iterate.

Syntax of while Loop in Python
while test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one
iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

Body starts with indentation and the first unindented line marks the
end.

Python interprets any non-zero value as True. None and 0 are
interpreted as False.
Flowchart
Example
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
OUTPUT :
Enter n: 10
The sum is 55

while loop with else

Same as that of for loop, we can have an
optional else block with while loop as well.

The else part is executed if the condition in the
while loop evaluates to False.

The while loop can be terminated with a break
statement. In such case, the else part is
ignored. Hence, a while loop's else part runs if
no break occurs and the condition is false.

Example to illustrate
# the use of else statement
# with the while loop

counter = 0

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Output:
Inside loop
Inside loop
Inside loop
Inside else

While with The break Statement

The break Statement

With the break statement we can stop the loop even if the
while condition is true:

Example

Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
I += 1
Output:
1
2
3
While with The continue Statement

With the continue statement we can stop the
current iteration, and continue with the next:

Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
12456

What is the use of break and
continue in Python?

In Python, break and continue statements can alter the flow of a
normal loop.

Loops iterate over a block of code until test expression is false, but
sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression.

The break and continue statements are used in these cases.

Python break statement

The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the loop.

If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.

Syntax of break

break
Flowchart

Python continue statement

The continue statement is used to skip the rest
of the code inside a loop for the current iteration
only. Loop does not terminate but continues on
with the next iteration.

Syntax of Continue

continue
Flowchart

What is pass statement in Python?

In Python programming, pass is a null statement. The
difference between a comment and pass statement in Python
is that, while the interpreter ignores a comment entirely, pass
is not ignored.

However, nothing happens when pass is executed. It results
into no operation (NOP).

Syntax of pass

pass

We generally use it as a placeholder.

Suppose we have a loop or a function that is not implemented
yet, but we want to implement it in the future. They cannot
have an empty body. The interpreter would complain. So, we
use the pass statement to construct a body that does nothing.
Example
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

You might also like