Looping constructs
Looping constructs
Printing Numbers
• Write a Python code to print the first N natural
numbers.
PAC - Printing Numbers
Input Processing Output
• for statement
– Repeatedly executes a set of statements until the
sequence is exhausted
Syntax of while in Python
# Loop test (condition is true)
while test:
statements # Loop body
statements
Note the colon (:) following test and else and the indentation
Example: Printing first ‘N’ numbers
Let N=3
counter =1
while counter <= N:
print(counter)
counter = counter + 1
Output:
123456789
Let N=3
counter =1
while counter <= N:
if N%2!=0:
continue #skips the current iteration
print(counter)
counter = counter + 1
Class Average
• Given marks secured in CSE1001 by the
students in a class, design an algorithm and
write a Python code to determine the class
average. Print only two decimal digits in
average
Class Average
Input Processing Output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
For and Range
for n in range(1, 6):
print(n)
Output when the above code is executed:
1
2
3
4
5
range function call
Syntax - range( begin,end,step )
where
Begin - first value in the range; if omitted, then default value
is 0
end - one past the last value in the range; end value may not
be omitted
Step - amount to increment or decrement; if this parameter
is omitted, it defaults to 1 and counts up by ones
Output:
2
4
6
8
Try it
• Print even numbers from N to 1
• Print only odd numbers from 1 to N
Pattern Generation - Code
Test Cases
Input
-1
Output
Invalid input
Processing Involved
Boundary condition check fails
Test Cases
Input
3
Output
#
##
###
Processing Involved
Print step by step
Try it
• Write pseudocode and python code to print
the pattern structure given the value of n.
– For example, the following structure should be
displayed for n=4.
####
###
##
#
Try it
• Write pseudocode and python code to print
the pattern structure given the value of n.
– For example, the following structure should be
displayed for n=4.
1
22
333
4444