0% found this document useful (0 votes)
4 views

Python Programming (Unit-2)

The document provides an overview of Python programming focusing on control flow statements including conditional blocks (if, else, elif) and loops (for, while). It explains the syntax and usage of these statements with examples, demonstrating how they can be utilized to control the execution flow of a program. Additionally, it covers loop control statements such as break, continue, and pass, along with practical programming examples.

Uploaded by

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

Python Programming (Unit-2)

The document provides an overview of Python programming focusing on control flow statements including conditional blocks (if, else, elif) and loops (for, while). It explains the syntax and usage of these statements with examples, demonstrating how they can be utilized to control the execution flow of a program. Additionally, it covers loop control statements such as break, continue, and pass, along with practical programming examples.

Uploaded by

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

KALI CHARAN NIGAM INSTITUTE OF

TECHNOLOGY, BANDA

“PYTHON PROGRAMMING”
BCC-402
UNIT – II

Python Program Flow Control Conditional blocks: if, else and else
if (elif), Simple for loops in python, for loop using ranges, string, list
and dictionaries. Use of while loops in python, Loop manipulation
using pass, continue, break and else. Programming using Python
conditional and loop blocks.

Compiled by
Abhishek Tiwari
(Assistant Professor)
Control Flow Statements
Python control flow. Control flow is the order in which individual statements, instructions, or
function calls are executed or evaluated. The control flow of a Python program is regulated by
conditional statements, loops, and function calls.

In Python, there are three types of control flow statements:

 Decision-making statements: Evaluate a Boolean expression and control the program


flow.
 Loop statements: Execute a set of instructions repeatedly.
 Jump statements: Transfer the control of the program to specific statements.
Control statements help with implementing decision-making in a program. They can make
programs and algorithms clearer and easier to understand.

Python if statement

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

Syntax of If Statement in Python:

#if syntax Python

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

Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, Python uses indentation to identify a block. So the block under the Python if
statements 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.

Flowchart of Python If Statement


Let’s look at the flow of code in the Python If statements.
Example of Python if Statement
As the condition present in the if statements in Python is false. So, the block below the if
statement is executed.

# python program to illustrate If statement


i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Output:
I am Not in if

Python If Else Statement

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 if we want to do something else if the condition is
false, we can use the else statement with the if statement Python to execute a block of code
when the Python if condition is false.

Syntax of If Else in Python


if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flowchart if else statement in Python
Let’s look at the flow of code in an if else Python statement.
Using Python If Else Statement
The block of code following the else if in Python, the statement is executed as the condition
present in the if statement is false after calling the statement which is not in the block(without
spaces).

# python program to illustrate else if in Python statement


#!/usr/bin/python

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

If Else in Python using List Comprehension


In this example, we are using an Python else if statement in a list comprehension with the
condition that if the element of the list is odd then its digit sum will be stored else not.
Python

# Explicit function
def digitSum(n):
dsum = 0
for ele in str(n):
dsum += int(ele)
return dsum

# Initializing list
List = [367, 111, 562, 945, 6726, 873]

# Using the function on odd elements of the list


newList = [digitSum(i) for i in List if i & 1]

# Displaying new list


print(newList)
Output :

[16, 3, 18, 18]

Nested-If Statement in Python


A nested if is an if statement that is the target of another if statement. Nested if statements
mean 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 of Python Nested if Statement


Let’s look at the flow of control in Nested if Statements

Example of Python Nested if statement


In this example, we are showing nested if conditions in the code, All the If condition in
Python will be executed one by one.

# 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

Python 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 of Python if-elif-else ladder


Let’s look at the flow of control in if-elif-else ladder:
Example of Python if-elif-else ladder
In the example, we are showing single if in Python, multiple elif conditions, and single else
condition.
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python

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

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block then shorthand
if can be used. The statement can be put on the same line as the if statement.

Syntax:
if condition: statement

Example of Python if shorthand


In the given example, we have a condition that if the number is less than 15, then further
code will be executed.

# Python program to illustrate short hand if


i = 10
if i < 15: print("i is less than 15")
Output:
i is less than 15

Short Hand if-else statement


This can be used to write the if-else statements in a single line where only one statement is
needed in both the if and else blocks.
Syntax:
statement_when_True if condition else statement_when_False

Example of Python if else shorthand


In the given example, we are printing True if the number is 15, or else it will print False.

# Python program to illustrate short hand if-else


i = 10
print(True) if i < 15 else print(False)
Output:
True
Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all the techniques is the same, although the
syntax and the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Name of
Sr.No. Loop Type & Description
the loop
While loop Repeats a statement or group of statements while a given condition is TRUE.
1 It tests the condition before executing the loop body.
For loop This type of loop executes a code block multiple times and abbreviates the
2 code that manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.

The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.
Syntax of the for Loop
for value in sequence:
{ code block }
In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
# Python program to show how the for loop works

# Creating a sequence which is a tuple of numbers


numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

# variable to store the square of the number


square = 0

# Creating an empty list


squares = []
# Creating a for loop
for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence element is reached. The
statement is written right after the for loop is executed after the execution of the for loop is
complete.

Only if the execution is complete does the else statement comes into play. It won't be executed
if we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

# Python program to show how if-else statements work

string = "Python Loop"

# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)

Output:

P
y
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.


Syntax:

for value in sequence:


# executes the statements until sequences are exhausted
else:
# executes these statements when for loop is completed

Code

# Python program to show how to use else statement with for loop

# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)

# Initiating the loop


for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
print("These are the odd numbers present in the tuple")

Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function

With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size).
If the step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.

The example that follows will make this clear.

Code
# Python program to show the working of range() function

print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))

Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops. We can
use indexing to iterate through the given sequence by combining it with an iterable's len()
function. Here's an illustration.

Code
# Python program to iterate over a sequence with the help of indexing

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")

# iterating over tuple_ using range() function


for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop

While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.

Syntax of the while loop is:

while <condition>:
{ code block }
All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements together
with indentation.

Code

# Python program to show how to use a while loop


counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

Output:

Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement with the while loop
also. It has the same syntax.

Code

#Python program to show how to use else statement with the while loop
counter = 0
# Iterating through the while loop
while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
# Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block


The loop can be declared in a single statement, as seen below. This is similar to the if-else
block, where we can write the code block in a single line.

Code

# Python program to show how to write a single statement while loop


counter = 0
while (count < 3): print("Python Loops")

Loop Control Statements (Jumping Statements)


Now we will discuss the loop control statements in detail. We will see an example of each
control statement.

Continue Statement

It returns the control to the beginning of the loop.

Code

# Python program to show how the continue statement works

# Initiating the loop


for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement

It stops the execution of the loop when the break statement is reached.

Code

# Python program to show how the break statement works

# Initiating the loop


for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)

Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.

Code

# Python program to show how the pass statement works


for a string in "Python Loops":
pass
print( 'Last Letter:', string)

Output:

Last Letter: s

Programming using Python conditional and loop blocks


if statement

age = 18

if age >= 18:


print("You are old enough to vote.")

if else statement
age = 16

if age >= 18:


print("You are old enough to vote.")
else:
print("You are not old enough to vote yet.")

if elif else statement


age = 16

if age >= 18:


print("You are old enough to vote.")
elif age >= 16:
print("You can drive but cannot vote.")
else:
print("You cannot drive or vote yet.")

While Loop Statement:


count = 1
while count <= 5:
print(count)
count += 1

For Loop Statement:


word = "Python"
for letter in word:
print(letter)

You might also like