Loop Structure in Python
1) while
2) for
while: used to execute instructions repeatedly till the condition is true.
while condition: while condition:
Statement1 Statement1
Statement2 Statement2
else:
Statement3
Statement4
else block is optional. If present, it is executed when condition fails.
If the while loop is terminated abruptly using a break, then the else block is not executed.
while 1: infinite loop.
while True: again an infinite loop.
for:
for var in list: for var in list:
statement1 statement1
statement2 statement2
else:
statement3
statement4
During each iteration, var is assigned the next value from the list.
In place of a list, a string, tuple, set or dictionary can also be used.
else block is optional. If present, it will be executed if loop is not terminated by keyword break
range():
range() function generates a sequence of integers.
Syntax: range([start,] stop, [step]) start (inclusive), stop (exclusive)
If start value is not specified, it would always be considered as zero.
range(10) generates numbers from 0 to 9.
range(10,20) generates numbers from 10 to 19.
range(10,20,2) generates sequence 10 12 14…18.
range(20,10,-3) generates sequence 20 17 14…11.
range() can’t generate a sequence on floats.
A for loop and range()
for i in range(1,10,2):
print(i,i*i,i*i*i)
A for loop and string, list, tuple, set or dictionary
We can use for loop to iterate through a string, list, tuple, set or dictionary. Look at various examples:
string: for char in 'PDPU':
print(char, end=' ')
list: for animal in ['cat', 'dog', 'tiger', 'lion', 'leopard']:
print(animal, end=' ')
tuple: for flower in ('Rose', 'Lily', 'jasmine'):
print(flower, end=' ')
set: for num in { 10,20, 30, -20, -50}:
print(num, end=' ')
dictionary for key in { 'a101':'SoT', 'a102':'SoET', 'a103':'SLS', 'a104': 'SoM' }:
print(key, end=' ')
enumerate(): to print the index value.
ls = ['cat', 'dog', 'tiger', 'lion', 'leopard']
for i, ele in enumerate(ls):
print(i, ele)
break and continue:
Both can be used with for and while.
break terminates the loop without executing the else block.
Continue skips the rest of the statements in the block and continues with the next iteration of the loop.
else block of a loop:
else block of a while loop should be used in situations where you wish to execute some statements if the loop is
terminated normally and not if it is terminated abruptly.
The pass statement:
The pass statement doesn’t do anything.
Used with if or within loop.
Exercise:
1) Print all alphabets in upper case and in lower case.
2) Print a multiplication table of a given number.
3) Count no. of alphabets and no. of digits in any given string.
4) Check whether a given number is prime, is perfect, is Armstrong, is palindrome, is automorphic.
5) Generate all Pythagorean Triplets with side length <= 30.
6) Print 24 hours of day with suitable suffixes like AM, PM, Noon and Midnight.
7) Print nCr and nPr.
8) Print factorial of a given number.
9) Print N natural nos. in reverse.
10) Generate N numbers of Fibonacci series.
11) Calculate sin(x); x is a radian value. The formula is as under:
3 5 7
x x x
sin x=x− + − …
3! 5! 7!
(hint: degrees can be converted into radians by 3.14159 / 180.)