0% found this document useful (0 votes)
2 views18 pages

python un 2

This document provides an overview of selection and iterative statements in Python, including if, if-else, if-elif, and loops like while and for. It explains the syntax and usage of these statements, along with examples and outputs to illustrate their functionality. Additionally, it covers nested loops, jump statements (break, continue, pass), and their applications in controlling the flow of a program.

Uploaded by

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

python un 2

This document provides an overview of selection and iterative statements in Python, including if, if-else, if-elif, and loops like while and for. It explains the syntax and usage of these statements, along with examples and outputs to illustrate their functionality. Additionally, it covers nested loops, jump statements (break, continue, pass), and their applications in controlling the flow of a program.

Uploaded by

rajalakshmicom85
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-II PYTHON PROGRAMMING

______________________________________________________________________________

SELECTION/CONDITIONAL BRANCHING STATEMENTS


In Python, the selection statements are also known as decision making statements or
branching statements. The selection statements are used to select a part of the program to be
executed based on a condition. Python provides the following selection statements.

 if statement
 if-else statement
 if-elif statement

if statement in Python
In Python, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If it is True, then the block of statements is
executed and if it is False, then the block of statements is ignored. The execution flow of if
statement

general syntax

if condition:
Statement_1
Statement_2
Statement_3
...

1
#if syntax Python

if condition:
# Statements to execute if
# condition is true
num = 5

if num > 0:
print("The number is positive.")
Output:
The number is positive.

Flowchart of If Statement

When we define an if statement, the block of statements must be specified using indentation
only. The indentation is a series of white-spaces. Here, the number of white-spaces is variable,
but all statements must use the identical number of white-spaces

if-else statement in Python


In Python, we use the if-else statement to test a condition and pick the execution of a
block of statements out of two blocks based on that condition result. The if-else statement checks
the given condition then decides which block of statements to be executed based on the condition
result. If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed. The execution flow of if-else statement

2
The general syntax

if condition:
Statement_1
Statement_2
Statement_3
...
else:
Statement_4
Statement_5
...
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

In the above syntax, whenever the condition is True, the statements 1 2 and 3 are gets executed.
And if the condition is False then the statements 4 and 5 are gets executed.

3
num = -5

if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
Output:

The number is negative.

Flowchart

If-elif-else statement in Python


In Python, When we want to test multiple conditions we use elif statement.
The general syntax
if condition_1:
Statement_1
Statement_2
Statement_3
...
elif condition_2:
Statement_4
Statement_5

4
Statement_6
...
else:
Statement_7
Statement_8
...
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

In the above syntax, whenever the condition_1 is True, the statements 1 2 and 3 are gets
executed. If the condition_1 is False and condition_2 is True then the statements 4, 5, and 6 are
gets executed. And if condition_1 nad Condition_2 both are False then the statements 7 and 8 are
executed.

5
score = 85

if score >= 90:


grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"

print("Your grade is:", grade)

Output:

Your grade is: B


Nested if Statement
Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement.
There may be a situation when you want to check for additional conditions after the initial one
resolves to true. In such a situation, you can use the nested if construct.
Additionally, within a nested if construct, you can include an if...elif...else construct inside
another if...elif...else construct.

Syntax of Nested if Statement


if expression1:
statement(s)
if expression2:

6
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)

num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

output −
num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3
Print Page

ITERATIVE STATEMENT
In Python, an iterative statement (also known as a loop) is a control flow statement that allows
the programmer to execute a block of code repeatedly until a certain condition is met. There are
two types of iterative statements in Python: 1. `for` loop: This loop is used for iterating over a
sequence...

7
WHILE LOOP
Python While Loop is used to execute a block of statements repeatedly until a given condition
is satisfied. When the condition becomes false, the line immediately after the loop in the
program is executed.

While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance.
Statements represent all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements. When a while loop is executed, expr is first
evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is
checked again, if it is still true then the body is executed again and this continues until the
expression becomes false.

Syntax of while loop in Python


while expression:
statement(s)

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek

8
INFINITE LOOP IN PYTHON
We can create infinite loops in Python via the while statement. In a loop, the variable is
evaluated and repeatedly updated (while the given condition is True). We can create an infinite
loop in Python if we set the condition in a way that it always evaluates to True.

a=1
while a==1:
b = input(“what’s your name?”)
print(“Hi”, b, “, Welcome to Intellipaat!”)

Output:
what’s your name?
Akanksha Rana #user input
Hi Akanksha Rana , Welcome to Intellipaat!

what’s your name?


Amrit #user input
Hi Amrit , Welcome to Intellipaat!

Do While Loop
Python doesn’t have a do-while loop. But we can create a program to implement do-while. It is
used to check conditions after executing the statement. It is like a while loop but it is executed at
least once.
i=1

while True:

print(i)

i=i+1

if(i > 5):

break

The output will be

9
1

For Loops
The For Loops in Python are a special type of loop statement that is used for sequential
traversal. Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or
Dictiona ry.
In Python, there is no C style for loop, i.e., for (i=0; I <n; i++). The For Loops in Python is
similar to each loop in other languages, used for sequential traversals.

Python For Loop Syntax


for var in iterable:
# statements
print("String Iteration")

s = "Geeks"
for i in s:
print(i)
Output:
String Iteration
G
e
e
k
s

10
Nested For Loops in Python
This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive)
and prints the value of i and j for each combination of the two loops. The inner loop is executed
for each value of i in the outer loop. The output of this code will print the numbers from 1 to 3
three times, as each value of i is combined with each value of j.

for i in range(1, 4):


for j in range(1, 4):
print(i, j)
Output :
11
12
13
21
22
23
31
32
33

ELSE SUITE IN LOOP


Python supports an else clause in for and while loops. The else body is executed only if
no break is encountered during the execution of the associated loop body. In one of the scenarios
where this can be quite useful is when you are searching for a particular value in the loop and the
value is not found.

Else with loop is used with both while and for loop. The else block is executed at the end of
loop means when the given loop condition is false then the else block is executed. So let’s see
the example of while loop and for loop with else below.

Else with While loop


i=0

while i<5:
i+=1
print("i =",i)

else:
print("else block is executed")
11
Output:
i=1
i=2
i=3
i=4
i=5
else block is executed
Explanation
 declare i=0
 we know then while loop is active until the given condition is true. and we check i<5 it’s
true till the value of i is 4.
 i+=1 increment of i because we don’t want to execute the while loop infinite times.
 print the value of i
 else block execute when the value of i is 5.

Else with For loop

l = [1, 2, 3, 4, 5]

for a in l:
print(a)

else:
print("else block is executed")
Output:
1
2
3
4
5
else block is executed
Explanation
 declare a list l=[1,2,3,4,5]

12
 for loop print a.
 else block is execute when the for loop is read last element of list.

Python Nested Loops


In Python programming language there are two types of loops which are for
loop and while loop. Using these loops we can create nested loops in Python. Nested loops
mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for
loop, etc.

Python Nested Loops Syntax:


Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop

x = [1, 2]
y = [4, 5]

for i in x:
for j in y:
print(i, j)
Output:
14
15
24
25

13
Using break statement in nested loops
It is a type of loop control statement. In a loop, we can use the break statement to exit
from the loop. When we use a break statement in a loop it skips the rest of the iteration and
terminates the loop.
for i in range(2, 4):

# Printing inside the outer loop


# Running inner loop from 1 to 10
for j in range(1, 11):
if i==j:
break
# Printing inside the inner loop
print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()

Output:
2*1=2

3*1=3
3*2=6

JUMP STATEMENTS

Jump statements in Python are used to control the flow of code and alter the normal sequential
execution of statements. They allow the programmer to skip over certain sections of code,
terminate loops prematurely, or skip specific iterations of a loop

The three types of jump statements in Python are:


- Break statement: Terminates the loop prematurely and resumes the execution of the code
outside the loop.
- Continue statement: Skips the remaining statements in the current iteration of the loop and
resumes execution at the next iteration.
- Pass statement: Acts as a placeholder statement that does nothing, used to represent an empty
block of code or as a temporary placeholder for code that will be added later.

14
Python break statement
Python break is used to terminate the execution of the loop. break statement
in Python is used to bring the control out of the loop when some external condition is triggered.
break statement is put inside the loop body (generally after if condition). It terminates the
current loop, i.e., the loop in which it appears, and resumes execution at the next statement
immediately after the end of that loop. If the break statement is inside a nested loop, the break
will terminate the innermost loop.

Syntax:
Loop{
Condition:
break
}

for i in range(10):
print(i)
if i == 2:
break

Output:

0
1
2
num = 0
for i in range(10):
num += 1

15
if num == 8:
break
print("The num has value:", num)
print("Out of loop")

Output
The num has value: 1
The num has value: 2
The num has value: 3
The num has value: 4
The num has value: 5
The num has value: 6
The num has value: 7
Out of loop

Python Continue Statement


Python Continue Statement skips the execution of the program block after the
continue statement and forces the control to start the next iteration.

Python Continue statement is a loop control statement that forces to execute the next
iteration of the loop while skipping the rest of the code inside the loop for the current iteration
only, i.e. when the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped for the current iteration and the next iteration of the loop
will begin.

Syntax
while True:
...
if x == 10:
continue
print(x)

16
for var in "Geeksforgeeks":
if var == "e":
continue
print(var)

Output:

G
k
s
f
o
r
g
k
s

Python pass Statement


17
The Python pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass is not ignored.

When the user does not know what code to write, So user simply places a pass at that
line. Sometimes, the pass is used when the user doesn’t want any code to execute. So users can
simply place a pass where empty code is not allowed, like in loops, function definitions, class
definitions, or in if statements. So using a pass statement user avoids this error.

Syntax

pass
def function():
pass

li =['a', 'b', 'c', 'd']

for i in li:
if(i =='a'):
pass
else:
print(i)

Output:
b
c
d

18

You might also like