Python for loop

  • for loop is used for iterating over a sequence
  • sequence can be a list, a tuple, a dictionary, a set, or a string.
  • for loop has a finite number of iterations

Prerequisites

for loop syntax

for val in sequence:
    statement
  • write a program to print all names in a given list.
  • the names are "Anji", "Harika" and "Angelica"
names = ["Anji", "Harika", "Angelica"]
for name in names:
    print(name)
# Output:
# Anji
# Harika
# Angelica

use continue keyword with for loop

  • use continue keyword when we want to skip the execution of an iteration

write program to print square of the given numbers i.e numbers = [1,2,3,4,5,6] and skip the number if number divisible by 3

numbers = [1,2,3,4,5,6]

for num in numbers:
    if(num % 3 == 0):
        print(f'skipped num={num}')
        continue
    print(f'square = {num**2}')
# Output:
# square = 1
# square = 4
# skipped num=3
# square = 16
# square = 25
# skipped num=6

use range() with for loop

  • range() is builtin python function to create a range of numbers.
  • syntax: range(start, end, step)
  • default start=0, step=1

write a program to print numbers from 1 to 5 using range() function.

for num in range(1, 6):
    print(num)
# output:
# 1
# 2
# 3
# 4
# 5

write a program to print even numbers between 0 and 5 using range() function.

for num in range(2, 6, 2):
    print(num)
# output:
# 2
# 4

use break keyword in for loop

  • use break keyword if we want to stop the execution of for loop.

write a program to print all numbers in given list of numbers but if stop the execution if numer 7 found.

numbers = [1,2,7,3,4]
for num in numbers:
    if num == 7:
        break
    print(num)
# output
# 1
# 2

nested for loop

  • for loop can be nested if required

write program to print permutations of a string

string = "ABC"
for l1 in string:
    for l2 in string:
        print(l1, l2)
# output:
# A A
# A B
# A C
# B A
# B B
# B C
# C A
# C B
# C C

word freequency counter

write a program to count total number words in a given text.

text = 'You know New York, you need New York'

words_list = text.split();
counter = {}
for word in words_list:
    word_count = counter.get(word)
    if word_count is None:
        counter[word] = 1
    else:
        counter[word] = counter[word] + 1
print(counter)
# output: {'You': 1, 'know': 1, 'New': 2, 'York,': 1, 'you': 1, 'need': 1, 'York': 1}

References