for StatementThe for statement allows you to iterate over the elements of a sequence (iterable), such as a variable of type list, tuple or str.
Syntax
for iterating_var in sequence :
statement(s)
strExample: display only the consonants of a string.
string = 'Python programming language'
vowels = 'aeiou'
for char in string :
if char not in vowels :
print(char, end='')
tupleExample: calculate the sum of the integer elements of a tuple.
numbers = (1,4,9,16,25)
s = 0
for num in numbers :
s += num
print('Sum = ', s)
listExample: calculate the sum of the integer elements of a list.
numbers = [1,4,9,16,25]
s = 0
for num in numbers :
s += num
print('Sum = ', s)
range() functionThe predefined function range() returns an iterator that generates an integer at each iteration.
The iterator generates integers in a range starting at a start value and ending at an end value with an increment step.
Syntax
range(start, stop, step)
Parameters
start: start value of the range of values. The default value is 0.stop: values go up to the value stop - 1.step: increment step value. The default value is 1.Example
for num in range(5, 55, 5) :
print(num, end=' ')
The range() function allows you to obtain the indices of a sequence and thus iterate over them.
Syntax
range(len(sequence))
Example
numbers = [1,4,9,16,25,36]
indices = range(len(numbers))
for index in indices :
print(f'index: {index} number: {numbers[index]}')
dictIterating over a dict uses the values of the key component of the pairs constituting the dict.
Example
numbers = {10:'Ten', 20:'Twenty', 30:'Thirty', 40:'Forty'}
for k in numbers :
print(k)
When accessing the value of the key component of a pair, we can also access the value of the value component of that pair using the bracket operator [ ].
Example
numbers = {10:'Ten', 20:'Twenty', 30:'Thirty', 40:'Forty'}
for k in numbers :
print(k,':', numbers[k])
The dict class has the methods items(), keys() and values() which return dict.items(), dict.keys() and dict.values() objects respectively.
These objects are iterators used to iterate in a for loop.
The dict.items() object is a list of (key,value) pairs.
This object can be used to iterate in a for loop.
Example
numbers = {10:'Ten', 20:'Twenty', 30:'Thirty', 40:'Forty'}
for p in numbers.items() :
print(p)
Example
numbers = {10:'Ten', 20:'Twenty', 30:'Thirty', 40:'Forty'}
for k,v in numbers.items() :
print(k, ':', v)
The dict.keys() object is a collection of the values of the key component of (key,value) pairs.
This object can be used to iterate in a for loop.
Example
numbers = {10:'Ten', 20:'Twenty', 30:'Thirty', 40:'Forty'}
for k in numbers.keys() :
print(k, ':', numbers[k])
Example: multiplication tables.
for m in range(1, 11) :
for n in range(1, 11) :
p = m * n
print (f'{p:3d}', end=' ')
print()
while StatementThe while loop allows you to iterate a block of statements as long as the value of a boolean expression is True.
Syntax
while boolean_expression :
statement(s)
Example
count = 0
while count < 5 :
count += 1
print('Iteration no. ', count)
print('End of while loop')
break StatementThe break statement is used to terminate a current loop and resume execution at the next statement.
The break statement is used in a for or while loop.
Example: Stop iterations if a negative integer is found among the elements of a list.
numbers = [2,5,-7,8,13]
for num in numbers :
print(num)
if num < 0 :
print('negative number found, exit loop')
break
continue StatementThe continue statement is used to stop the execution of the current iteration in a loop, and then continue the loop by executing the next iteration.
The continue statement is used in a for or while loop.
Example: display only positive numbers among the elements of a list of integers.
numbers = [2,5,-7,8,13]
for num in numbers :
if num < 0 :
continue
print(num)
else statement in a for or while loopAn else statement is used in a for or while loop to execute a block of statements upon exiting the loop.
Syntax
for iterating_var in sequence :
# statements in the loop
statement(s)
else :
# statement in the else clause
statement(s)
The else statement is not executed when the loop is terminated by a break statement.
Example: searching for an integer entered by the user in a list of integers.
n = int(input('enter an integer: '))
numbers = [1,4,9,16,25,36,49,64,81]
for num in numbers :
if num == n :
print ('number found in list')
break
else :
print ('number not found in list')