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

Python Control Statements Explained

Class 12 ip notes cbse

Uploaded by

schoolvaishnavi5
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)
9 views16 pages

Python Control Statements Explained

Class 12 ip notes cbse

Uploaded by

schoolvaishnavi5
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

INFORMATICS PRACTICES (065)

(c) Iteration/looping statements


 These statements will execute again and again for specific number of times or until condition’s
result is False.
 In python, there are two types of loop. They are
(a) for loop (counting loop)
(b) while loop (conditional loop)
(a) for loop (counting loop)
 This is counting loop, i.e. this loop will execute for specific number of times.
Syntax:
for var in range/sequence:
#for body

 for loop will applied on range()/sequence.


range()
This is a pre-defined function which is used to get the values in ranges.
Syntax:
range(start,stop,step)

 start: Starting number of the sequence.


 stop: Generate numbers up to, but not including this number.
 step: Difference between each number in the sequence.
Note-1: All parameters must be integers (may be positive or negative).

Note-2: Atleast one parameter must be there in python. If there is only one
parameter, then it will be considered as ‘stop’ value. If there will be two
parameters, then these will be ‘start’ and ‘tart’ respectively.

Eg(1): range(6) generates the numbers from [0,1,2,3,4,5].

Eg(2): range(2,6) generates the numbers from [2,3,4,5].

Eg(3): range(2,10,2,) generates the numbers from [2,4,6,8].

Eg(4): range(1,10,2,) generates the numbers from [1,3,5,7,9].

Eg(5): range(10,1,-2,) generates the numbers from [10,8,6,4,2].

CONTROL STATEMENTS 49
INFORMATICS PRACTICES (065)

 If range() function will generate ‘n’ number of values, then the ‘for’ loop will
execute for ‘n’ times.
 In ‘for’ syntax, ‘var’ is the variable that takes the value of the item inside the sequence
on each iteration.

Flowchar for ‘for’ syntax:

For each item


Sequence /range

Last Item Yes


Reached?
No

Exit Loop

Statement1

Eg(1):
for i in range(1,6):
print(i)

Output:
1
2
3
4
5
Note: in above example, range generates numbers from ‘1’ upto ‘6’,but not including ‘6’.
Eg(2):
for i in range(1,6):
print(i,end=' ')

Output:
12345

Eg(3):
for i in range(6):
print(i,end=' ')

CONTROL STATEMENTS 50
INFORMATICS PRACTICES (065)

Output:
012345
Note: in above example, there is start value. The range will starts from 0(zero), if there is
no start value in range.

Eg(4):
for i in range(6,0,-1):
print(i,end=' ')

Output:
654321

Eg(5): Write a python program that displays the odd numbers and even numbers separately from
1 to given number.
#Filename: odd_even_nos.py

n=int(input('Enter number:'))
print('The Even Numbers Are:')
for i in range(2,n+1,2):
print(i,end=' ')
print('\nThe Odd Numbers Are:')
for i in range(1,n+1,2):
print(i,end=' ')

Output:
Enter number:10
The Even Numbers Are:
2 4 6 8 10
The Odd Numbers Are:
13579

Eg(6): Write a python program that find and displays the sum of natural numbers from 1 to given
number.
#Filename: sum_natual_nos.py

n=int(input('Enter number:'))
sum=0
for i in range(1,n+1):
sum+=i
print('The sum natural Nos=',sum)

CONTROL STATEMENTS 51
INFORMATICS PRACTICES (065)

Output:
Enter number:10
The sum natural Nos= 55
Eg(7): Write a python program that finds and displays the sum of odd and even numbers from 1
to given number.
#Filename: sum_odd_even_nos.py

n=int(input('Enter number:'))
sum1=0 #to store odd sum
sum2=0 #to store even sum
for i in range(1,n+1):
if i%2!=0: # here, checking whether 'i' value is odd or not
sum1+=i
else:
sum2+=i
print('The sum Odd Nos=',sum1)
print('The sum Even Nos=',sum2)

Output:
Enter number:10
The sum Odd Nos= 25
The sum Even Nos= 30
Eg(8): A simple python example that illustrates ‘for’ loop with sequence.

L=[10,20,30] #here, 'L' is a list


sum=0
for i in L:
sum+=i
print(sum)

Output:
60

Eg(9):
s='python' #here, 's' is a string
for i in s:
print(i)

CONTROL STATEMENTS 52
INFORMATICS PRACTICES (065)

Output:
p
y
t
h
o
n
Note: In above example, first ‘i’ value will be ‘p’, then ‘i’ value will be ‘y’ and so on..
(b) while loop (conditional loop)
This is conditional loop, i.e. the while loop will execute again and again until the condition’s result
is False.
Syntax:
while condition:
#whilebody

 Generally there will four steps in while loop. They are:


 Initialization expression (starting)
 Test Expression (Repeat/stop)
 While body (Doing/process of body)
 Update expression (changing)

Flowchart for “while” loop syntax

False
Condition1

True

While body

The statement that is outside of while loop

CONTROL STATEMENTS 53
INFORMATICS PRACTICES (065)

Eg(1):
n=int(input('Enter Number:'))
i=1
while i<=n:
print(i)
i+=1

Output:
Enter Number:5
1
2
3
4
5

Eg(2): Write a python program that find and displays the sum of natural numbers from 1 to given
number (using while loop).
#Filename: sum_natual_nos.py

n=int(input('Enter Number:'))
i=1
sum=0
while i<=n:
sum+=i
i+=1
print('Sum of natural Nos is:',sum)

Output:
Enter Number:10
Sum of natural Nos is: 55

Eg(3): Write a python program that find and displays the series of Fibonacci upto given value.
#Filename: Fibonacci_nos.py

n=int(input('Enter Number to print fibonacci series:'))


a=0
b=1
print('The fibonacci series is:')
print(a,end=' ')
c=a+b

CONTROL STATEMENTS 54
INFORMATICS PRACTICES (065)

while c<n:
print(c,end=' ')
c=a+b
a=b
b=c

Output:
Enter Number to print fibonacci series:100
The fibonacci series is:
0 1 1 2 3 5 8 13 21 34 55 89
3) Jumping Statements
There are two jumping statements in the loops of python. They are:
(a) break statement
(b) continue statement

(a) break statement


 It terminates the execution of the loop.
 Break can be used in while loop and for loop.
Flowchart of break

False
Condition1

True

Yes
break?

No
Remaining body
Exit Loop

Eg(1):
s='uselessfellow'
for i in s:
if i=='f':
break
else:

CONTROL STATEMENTS 55
INFORMATICS PRACTICES (065)

print(i)

Output:
u
s
e
l
e
s
s
Note: in above example, if ‘I’ value is ‘f’ then the ‘break’ will execute. That means, ‘for’ loop
execution will be aborted.

Eg(2):
a=10
for i in range(1,a+1):
if i==5:
break
else:
print(i)
print('hi')
print('EOP')

Output:
1
hi
2
hi
3
hi
4
hi
EOP
(b) 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.

CONTROL STATEMENTS 56
INFORMATICS PRACTICES (065)

Flowchart of continue

False
`Condition

True

Yes
continue

No
Remaining body

Exit Loop

Eg(1):
s='uselessfellow'
for i in s:
if i=='f':
continue
print('hello')
else:
print(i)

Output:
u
s
e
l
e
s
s
e
l
l
o
w
Note: In above example, if ‘i' value is ‘f’ then ‘continue’ will execute. Once ‘continue’ will execute
then print(‘hello’) doesn’t execute.
CONTROL STATEMENTS 57
INFORMATICS PRACTICES (065)

Eg(2): a=int(input('Enter number:'))


for i in range(1,a+1):
print('hi')
print('hello')
if i==2:
continue
print('uf')
print('bye')

Output:
Enter number:3
hi
hello
uf
bye
hi
hello
hi
hello
uf
bye

Note: In above example,


4) ‘else’ in loops
 We can use ‘else’ in ‘for’ or ‘while’ loops.
 ‘else’ part will executes in loops after successful completion of loop iterations.
 In case if loop will be aborted in middle of the execution, then ‘else’ doesn’t execute.

Eg(1):In the example, for loop ‘else’ part will execute, because ‘for’ will execute successfully.

s='python'
for i in s:
if i=='h':
pass
else:
print(i)
else:
print('End of the for loop::')

Output:

CONTROL STATEMENTS 58
INFORMATICS PRACTICES (065)

p
y
t
o
n
End of the for loop::

Eg(2): In the example, for loop ‘else’ part doesn’t execute, because ‘for’ loop execution will be
aborted when ‘i' value in ‘h’.

s='python'
for i in s:
if i=='h':
break;
else:
print(i)
else:
print('End of the for loop::')

Output:
p
y
t

Flowchart
 Flowchart is a pictorial representation of an algorithm to solve a problem.
 Symbols used in flowchart.

Start/Stop

Process

Condition / Decision
CONTROL STATEMENTS 59
INFORMATICS PRACTICES (065)

Flow Control

Connectors

Input/ Output

Eg(1): Write a Flowchart that finds addition of two given numbers:

Start

Read a
Read b

c=a+b

print c

Stop

CONTROL STATEMENTS 60
INFORMATICS PRACTICES (065)

Eg(2): Write a Flowchart that finds biggest among given two numbers:

Start

Read a
Read b

True False
a>b?

print a print b
is big is big

Stop

Pseudocode
The informal representation of steps to solve a problem is called pseudocode.
Eg(1): Write a pseudocode that finds biggest among given two numbers:
Sol:
Step1: start
Step2: read values into a and b
Step3: if a values is greater than b , then print a as an output, otherwise print ‘b’ as an output.
Step4: Stop

Decision Trees:
This is a tool that represent hierarchy of steps based on decisions.

Eg(1): Write a decision tree for the following problem.


The salesperson would like to deliver the food to house no.4 where there is sequence of houses
numbered from 1 to 10.

CONTROL STATEMENTS 61
INFORMATICS PRACTICES (065)

If houseNo!=4

False True

False
Deliver food
True If houseNo!=4

False True

Deliver food If houseNo!=4

False True

Nested loop:
 The loop with in the loop is called nested loop.
 The nested loops are used to represent rows and columns.
 The outer loop represents number of rows and the inner loop represent number of columns.
Eg (1): Write a python program that prints the pattern as follows.
1
22
333
4444
55555
666666
7777777
88888888
999999999
Solution:
Note: In the given problem, there are 9 rows. That’s why outer loop should execute for 9 times.
In first iteration one 1 should be printed, in second iteration two 2’s , 3rd iteration three 3’s
…should be printed. That’s why the inner loop should execute from 1 to iteration number
of times.
for i in range(1,10):
for j in range(1,i+1):
print(i,end='')
print()

Eg (2): Write a python program that prints the pattern as follows.


CONTROL STATEMENTS 62
INFORMATICS PRACTICES (065)

999999999
88888888
7777777
666666
55555
4444
333
22
1
Solution
for i in range(9,0,-1):
for j in range(i,0,-1):
print(i,end='')
print()
Eg (3): Write a python program that prints the pattern as follows.
1
12
123
1234
12345
123456
1234567
12345678
123456789
Solution:
for i in range(1,10):
for j in range(1,i+1):
print(j,end='')
print()
Eg (2): Write a python program that prints the pattern as follows.

123456789
12345678
1234567
123456
12345
1234
123
12
1
Solution:

CONTROL STATEMENTS 63
INFORMATICS PRACTICES (065)

for i in range(9,0,-1):
for j in range(1,i+1):
print(j,end='')
print()

CONTROL STATEMENTS 64

Common questions

Powered by AI

The 'for' loop in Python is used when the number of iterations is known beforehand and involves iterating over a sequence or range. It is a 'counting loop' and is particularly efficient when iterating over a list, range, or string, as it automatically handles the iteration of elements. The syntax for a 'for' loop involves a sequence or range function, which defines the start, stop, and step of the iteration . Conversely, the 'while' loop is a 'conditional loop' used when the number of iterations is not predetermined, as it continues execution until a specified condition is false. It requires explicit management of the loop's conditions, including initialization, testing, and updating of the loop variable .

Constructing a 'while' loop involves four key steps: Initialization expression, Test Expression, While Body, and Update Expression. Firstly, initialize a loop variable before the loop begins—this sets up the starting point of the iteration. Secondly, use a test expression that evaluates before each loop iteration; the loop will execute as long as this condition remains true. Thirdly, the loop body, consisting of the block of code to be repeated. Lastly, the update expression within the loop body modifies the loop variable, ensuring progression towards loop termination. These elements collectively enable the loop to execute correctly and eventually exit when the condition becomes false .

Nested loops, wherein one loop is placed inside another, are essential for generating complex numeric patterns due to their ability to handle multidimensional arrays like row and column structures. In design patterns like pyramids, triangles, or tables, the outer loop typically controls the number of rows, while the inner loop handles the columnar or repetitive elements within each row. For example, generating repeated numbers as rows increase, such as: ``` 1 22 333 4444 ... ``` can be accomplished with: ``` for i in range(1,10): for j in range(1,i+1): print(i,end='') print() ``` Careful attention must be paid to indentation, ensuring loops are properly nested, and output is formatted, often requiring specific handling of spaces or newline characters to achieve the desired pattern .

In Python, the 'range' function is used within 'for' loops to generate a sequence of numbers. It serves as a control structure for iterating over a series of integer values. The function can take up to three parameters: 'start', 'stop', and 'step'. The 'start' parameter specifies the beginning of the sequence and defaults to 0 if not provided. The 'stop' parameter determines the endpoint but is not included in the result. The 'step' parameter indicates the increment between each value in the sequence and defaults to 1 . Examples include 'range(6)' producing [0, 1, 2, 3, 4, 5] and 'range(2, 10, 2)' producing [2, 4, 6, 8].

A nested loop is ideal for printing patterns because it allows repetition over two dimensions—rows and columns. For an increasing sequence pattern such as: ``` 1 12 123 1234 ... ``` The nested loop structure ensures that for each iteration of the outer loop (controlled by variable 'i'), the inner loop (controlled by variable 'j') runs from 1 to i, printing incremental numbers. Example code is: ``` for i in range(1,10): for j in range(1,i+1): print(j,end='') print() ``` This code outputs a pattern where the nth row contains numbers from 1 to n .

The 'continue' statement in a loop acts differently from 'break' by skipping the rest of the code inside the loop for the current iteration without terminating the loop. It forces the loop to jump to the next iteration immediately. While 'break' completely exits the loop, 'continue' bypasses the remainder of the code for the current cycle but proceeds with the next iteration of the loop . For example, given a string s='uselessfellow', using 'continue' as follows: ``` for i in s: if i=='f': continue print(i) ``` The code outputs 'u s e l e s s e l l o w' and skips 'f', omitting the execution of any code following 'continue' within the loop body .

Decision trees offer advantages in algorithm representation by clearly presenting a hierarchical sequence of decision points and potential outcomes. They visually delineate the paths from decisions to their consequences, making complex, branching logic easier to understand and follow. This explicit representation is particularly beneficial in scenarios with multiple conditional branches or decisions, such as routing logic in applications or decision-making in games. For example, a decision tree can be used to route customer service inquiries based on predefined criteria, directing each query to the correct department based on the tree's logical flow. Such clarity directly aids in error identification and process optimization .

Pseudocode and flowcharts are crucial tools in algorithm design, serving as preliminary steps before coding. Pseudocode offers a high-level textual representation of the program logic, using plain language to outline the procedure in algorithm development. It provides clarity and insight into complex logic without dealing with specific syntax, facilitating communication among collaborators or stakeholders who may not be familiar with programming languages . Flowcharts complement pseudocode by offering a diagrammatic representation, using symbols to visualize processes and decision points. They help identify potential errors in logic, ensure that all scenarios have been considered, and provide a visual guide that simplifies the process of developing and debugging a program .

The 'break' statement is used to terminate the execution of a loop prematurely before it has run its full course. In Python, 'break' can be applied within both 'for' and 'while' loops. When the 'break' statement is executed, the loop immediately stops, and control is transferred to the statement following the loop. For instance, in a 'for' loop traversing a string, if a condition is met (e.g., the character 'f' is encountered), 'break' halts further iteration . An example code snippet is: ``` s='uselessfellow' for i in s: if i=='f': break print(i) ``` This code outputs 'u s e l e s s' and stops before 'f' .

The 'else' block in a loop is executed after the loop completes its iteration successfully without encountering a 'break' statement. In 'for' or 'while' loops, the 'else' statement is intended to run after the loop finishes its normal operation cycles. If a loop is prematurely terminated using 'break', the 'else' block does not execute. This mechanism is useful for implementing a concluding action contingent on the successful traversal of the entire looped sequence. For example: ``` s='python' for i in s: if i=='h': break else: print(i) else: print('End of the for loop::') ``` In this code, the output skips the 'else' statement because 'break' was executed when 'i' was 'h'. However, had the loop completed without 'break', the 'else' block would print 'End of the for loop::' .

You might also like