Sunday, May 17, 2026

Python Material - Part - 10 - Looping Statements

   For loop                                                                How break statement works

   

__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------

===================================================================================
                                PART -1
===================================================================================
"""
Topics to be covered in today's class:
--> Introduction to Loops or Control statements
--> for loop
--> While Loop
--> Nested Loops
--> Loop Control Statements (break, continue, pass)
--> Looping through Different Data Types
--> Advanced Loop Concepts

"""
"""
Introduction to Loops:
Why loop (control statements) concept required?
In general, statements are executed sequentially.
There may be a situation when you need to execute a block of code several number of times.

Python has 2 types of control statements/loops: while loop, for loop"""

"""
While loop:
A set of statements repeatedly executed until the given condition fails.
The loop control variable(i) must be manually updated within the loop to ensure progress toward terminating the loop.
If not handled properly, it can lead to infinite loops
"""

# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")
# print("Nanditha")
# print("Raahi")

# x = 1 # initialization
# while x <6: # Test condition
# print("Nanditha")
# print("Raahi")
# x+=1 # x =x+1 updation x =5+1


# num = 0
# while num < 10:
# print(num)
# num = num+1 # updation
#
# i = 0 # initialization
# while i < 14: # test condition
# print(i, end=", ")
# i = i+1 # updation
#


"""
For loop:
A for loop can be used to execute a group of statements repeatedly depending upon the number of elements/items in the iterable (list, tuple, dict, set)
In for loop, control variable is updated automatically (Ex: via range() or iterating over a collection).
The loop ends when all elements/items in the sequence are exhausted.

A for loop is used to iterate over a sequence (such as a list, tuple, dict, set, string, or range).

I would like to explain "for loop" in different ways:
==> for loop with range concept
==> for loop with enumerate concept
==> for loop with "Strings" concept
==> for loop with [List] concept
==> for loop with (Tuple) concept
==> for loop with {dictionary} concept
==> for loop with {set} concept
==> for loop with if condition
==> for loop with while loop
==> while loop & while with break and continue

==> Prefer enumerate() for counters
==> enumerate() yields(index,value)tuples
"""

"""range is a type of sequence used to representing arithmetic progression integers
range is a constructor returns a list.
range(5)==> range(0,5)==> [0, 1, 2, 3, 4]
syntax: range(start, stop, step value)
"""
# print(range(10)) # by default range function consider 0 as starting value"""
#



# a = [] # taking empty list
#
# for num in range(5,10):
# a.append(num) # append will add single element at the end
#
# print(a)
# print("Narendra")

#
# a = []
# for num in range(1, 11):
# a.append(num)
# print(a)
#
# a = []
# for num in range(11):
# a.append(num)
# print(a)

# a = []
# for narendra in range(5, 15):
# a.append(narendra)
# print(a)

# x = int(input("Enter starting value: "))
# y = int(input("Enter ending value: "))
# a = []
# for x in range(x, y+1, 2):
# a.append(x)
# print(a)


""" ******** Questions for students ********"""
"""Required Output : [1, 2, 3, 4, 5, 6, 7, 8, 9]"""
#
# a = []
# for swetha in range(1, 10):
# a.append(swetha)
# print(a)

"""Required Output : [1, 3, 5, 7, 9]"""

# a =[]
# for iter in range(1, 10, 2):
# a.append(iter)
# print(a)


""" Required Output : Reverse the given list
OR [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]"""
# a=[]
# for maha in range(10, 0, -1):
# a.append(maha)
# print(a)

"""Required Output : [10, 8, 6, 4, 2] """
# a = []
# for i in range(10, 0, -2):
# a.append(i)
# print(a)

#####################################################
# a = []
# for i in range(0, 100, 5):
# a.append(i)
# print(a)
#####################################################
# d = []
# for i in range(20, 0, -5):
# d.append(i)
#
# d.insert(2, "narendra")
# print(d)


##### user friendly program #######

# start_num = int(input("starting address: "))
# end_num = int(input("ending address: "))
# step_val = int(input("step address: "))
# output = []
# for i in range(start_num, end_num, step_val):
# output.append(i)
# print(output)

# even_numbers = []
# odd_numbers = []
# for num in range(15): # where num is iterator, range()/list/tuple/dict/set are iterables or sequences
# if num%2 == 0: # modulus operator will give you the reminder
# even_numbers.append(num)
# else:
# odd_numbers.append(num)
#
# print("even_numbers list from given sequence: ",even_numbers)
# print("odd numbers list from given sequence:", odd_numbers)

######################################################

""" ==> for loop with "Strings" concept (Iterating over a string)"""

# Data = "Narendra"
# for char in Data :
# print("character using for : ", char)

# Data = "Narendra Surendra"
# for char in Data :
# print("character using for", char)

Data = "Narendra"
# for i in range(Data): #TypeError: 'str' object cannot be interpreted as an integer
# print(i)


"""==> for loop with [List] concept (Iterating over a list) including if else conditions"""

"""Python code for separating even number and odd numbers from given input"""
data = [12, 55, 44, 22, 5, 7, 8, 4, 12, 6, 13, 3, 14, 119, 100, 15]
# for element in data:
# print(element)

data = [12, 55, 44, 22, 5, 7, 8, 4, 12, 6, 13, 3, 14, 119, 100, 15]
even = []
odd = []
for element in data:
if element % 2 == 0:
even.append(element)
else:
odd.append(element)

print("my even list is {} ".format(even))
print("my odd list is {}".format(odd))

"""
Given input: "Nenu Nanna Amma Bhagyasree Mahalakshmi Annyya Vadina lakshya-sree sathwika"
Required Output:
Nenu
Nanna
Amma
Bhagyasree
Mahalakshmi
Annyya
Vadina
lakshya-sree
sathwika
"""
data = "Nenu Nanna Amma Bhagyasree Mahalakshmi Annyya Vadina lakshya-sree sathwika".split() # return list of elements

# print(data)
# #
# for element in data:
# print(element)
# print("This is my beautiful family")

""" ######################################################
Practice program for students
######################################################"""


"""Required Output : [0, 2, 4, 6, 8]"""
# a=[]
# for iter in range(0, 9, 2):
# a.append(iter)
# print(a)

"""Required Output : [9, 7, 5, 3, 1]"""
# a=[]
# for i in range(9, 0, -2):
# a.append(i)
# print(a)

"""Write a python code to identify which is divisible by both 5 & 7 from range of numbers Ex: 1 to 100"""
output = []
# starting_address = int(input("starting address: "))
# ending_address = int(input("ending address : "))
# for number in range(starting_address, ending_address):
# if number % 5 == 0 and number % 7 == 0:
# output.append(number)
# print(output)

""" Iterating over a list """
# numbers = [1, 2, 3, 4, 5]
# for num in numbers:
# print("current number is", num)

===================================================================================
                                PART -2
===================================================================================

__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> for loop with enumerate concept
--> for loop with (tuple) concept (Iterating over a tuple)
--> for loop with {dictionary} concept
--> for loop with {set} concept
--> while loop with syntax
--> The Infinite Loop
--> break keyword, continue keyword
--> Interview questions on loop

"""
"""
==> for loop with enumerate concept
enumerate will give the index for the out sequence (list/tuple/set of elements or dictionary of items"""

Data = ['Nenu', 'Nanna', 'Amma', 'Bhagyasree', 'Mahalakshmi', 'Annyya', 'Vadina', 'lakshya-sree', 'sathwika']
# for element in Data:
# print(element)

# for i in enumerate(Data):
# print(i)

# for index, element in enumerate(Data): # we can use for enumerate for tuple
# print(index,"------->",element)
Data = ['Bhagyasree', 'Mahalakshmi', 'Surendra', 'Vadina', 'lakshya-sree', 'sathwika']
# for x, y in enumerate(Data):
# print(x+1,"-->", y)
#index
# for index,output_val in enumerate(Data):
# print("{0}_element, value={1}".format(index+1, output_val))

################################################################
# == > for loop with (tuple) concept (Iterating over a tuple)
Data = ('Nenu', 'Nanna', 'Amma', 'Bhagyasree', 'Mahalakshmi', 'Annyya', 'Vadina', 'lakshya-sree', 'sathwika')
# for i in Data:
# print(i)
# print("This is my beautiful family")

"""For loop with tuple along with Omiting starting address concept"""
data = ("Narendra","bhagyasree", "Nanna", "Amma", "Annyya", "Vadina")
# for i in data[ :3]: # prints sequence till "Nanna"
# print(i)

"""For loop with tuple along with Omiting Ending address concept"""
# data = ("Narendra","bhagyasree", "Nanna", "Amma", "Annyya", "Vadina")
# for name in data[2: ]: # prints from "Nanna" till end
# print(name)


""" tuple along with step element accessing using for loop"""
data = ("Narendra","bhagyasree", "Nanna", "Amma", "Annayya", "Vadina")

# for name in data[ : :2]:
# print(name)

""" for loop with tuple in terenary operator way"""
# numbers_tup = (15, 23, 25, 30, 33, 1116)
#
# print("tuple with finding numbers divisble by 5 with single line")
# for num in numbers_tup:
# print("{} is".format(num), "divisible by 5" if num % 5 == 0 else "not divisible by 5")

################################################################
"""
==> for loop with {dictionary} concept
By default looping over a dictionary, gives access to all the keys
"""
input_data = {"firstName": "Narendra",
"lastName": "Boyina",
"age": 27,
"sex": "M",
"salary": "xxxxx",
"registered": True}

"""On Dictionary, if you apply for loop, "i" by default it considers the keys only """
# for i in input_data:
# print(i)

# print(input_data.keys())
# print(input_data.values())

# for i in input_data.keys():
# print(i)

# for i in input_data.values():
# print(i)

# for key in input_data:
# print(input_data[key])

my_dict = {"firstName": "Narendra",
"lastName": "Boyina",
"age": 27,
"sex": "M",
"salary": "xxxxx",
"registered": True}

# for key, val in my_dict.items():
# print(key,"-------->", val)
#
# for a, (b, c) in enumerate(my_dict.items()):
# print(a, b,"-------->", c)

# for a, (b, c) in enumerate(my_dict.items()):
# print(a+1, b,"-------->", c)
################################################################

""""== > for loop with {set} concept"""

input_set = {"Nenu", "Nanna", "Amma", "Annyya", "Vadina", "Nanna"}
# print(input_set) # just printed, then by removing duplicate values, set datatype arranged elements in it's own order
# for i in input_set:
# print(i)
# o/p is arranged because set is Unordered collection of unique data

###############################################################
"""
while loop:

Repeats "a statement" or "group of statements" while a given condition is TRUE.
It tests the condition before executing the loop body.

We can use while loop for iterating "single statement / group of statements" infinite number of times.

Syntax of while loop:
====================
initializaton
while test_expression:
Body
value_update

"""

# count = 0 # initialization
# while count < 5: # test condition
# print('Present count is:', count)
# count += 1 # count = count + 1 # updation




"""1
Output:
Present count is: 0
Present count is: 1
Present count is: 2
Present count is: 3
Present count is: 4

Good bye!

"""
"""2. The Infinite Loop
Ex: Calucator addition (continuous inputs from user)"""

# W. A. P to take infinite values from the user

# radhika = 0 # initialization
# while True: # This constructs an infinite loop # test condition
# num = int(input(" Enter your interger input : ")) # body
# radhika = radhika+num # updation
# print("Total Value: ", radhika)
# print("Narendra")


"""
OUtput:
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number :"))
KeyboardInterrupt
"""

""" Using else Statement with Loops"""
# count = 0
# while count < 5:
# print(count, " is less than 5")
# count = count + 1
# else:
# print(count, " is not less than 5")

# """
# Output
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
# """
#
""" 4. Single Statement Suites"""

# flag = int(input("Enter True as 1/ False as 0 : "))
#
# while flag == 1:
# print('temparature sensor is damaged')
# print("Good bye!")

"""
break keyword will cause your while/for-loop stop executing and exit with out reaching the end of the iterable
# or the end of the range function"""

data = "Narendra love your work and do hard-work to reach your goal, don't be panic " \
"Don't think all the people will know all the things"

# b = data.split() # returns list
# print(b) # printing list

old_data = ['Narendra', 'love', 'your', 'work', 'and', 'do', 'hardwork', 'to', 'reach', 'your', 'goal,', "don't", 'be',
'panic', "Don't", 'think', 'all', 'the', 'people', 'will', 'know', 'all', 'the', 'things']

# for element in old_data:
# print(element)

# for element in old_data:
# if element == "panic":
# print("given condition is satisfied so exiting from this loop")
# break
# else:
# print(element)

old_data = ['Narendra', 'love', 'your', 'work', 'and', 'do', 'hardwork', 'to', 'reach', 'your', 'goal', "don't", 'be',
'panic', "Don't", 'think', 'all', 'the', 'people', 'will', 'know', 'all', 'the', 'things']
# new_data = []
# for element in old_data:
# if element == "panic":
# # print("given condition is satisfied so exiting from this loop")
# break
# else:
# new_data.append(element)

# print(new_data) # ['Narendra', 'love', 'your', 'work', 'and', 'do', 'hardwork', 'to', 'reach', 'your', 'goal,', "don't", 'be']
# d = " ".join(new_data)
# print(d)

# Simple way to write above code
# print(" ".join(old_data[ :old_data.index("panic")]))

"""
continue- keyword
by using continue keyword, we tell our iterater to skip particular value & executing the rest of the code.
except "panic" for print all the words in the list """

original_data = ['Narendra', 'love', 'your', 'work', 'and', 'do', 'hardwork', 'to', 'reach', 'your', 'goal,', "don't",
'be', 'panic', "Don't", 'think', 'all', 'the', 'people', 'will', 'panic', 'know', 'all', 'the', 'panic','things']
# print(original_data)
#
# new_data = []
# for element in original_data:
# if(element == "panic"): # this will skip the single specific word
# continue
# else:
# new_data.append(element)
# print(new_data)
#==================================================================
# new_data = []
# for element in original_data:
# if (element == "panic" or element == "all"): # this will skip the 2/ multiple specific words
# continue
# else:
# new_data.append(element)
# print(new_data)

# result:['Narendra', 'love', 'your', 'work', 'and', 'do', 'hardwork', 'to', 'reach', 'your',
# 'goal,', "don't", 'be', "Don't", 'think', 'all', 'the', 'people', 'will', 'know', 'all', 'the', 'things','Varun' ]"""

# ========== loops practice ========================================
# a=[]
# for i in range(0,12):
# a.append(i)
# print (a)
# print (a[0:10])
# print (a[10:15])
# print (a[9:-1])

"""Interview questions on loops: """
""" Question: How to replace a value in list multiple places at a time """
# hello will be replaced with Narendra
data= ["Hi", 444,"hello",472,"good morning",732,"hello",74.5,"hello", 34]
# print(data)
# for element in data :
# if element == "hello":
# b = data.index(element)
# data[b] = "Narendra" # replaced based on index
# print(data)
## # (OR)

# for element in data:
# if element == "hello":
# data[data.index(element)] = "Narendra"
# print(data)

# d = {0: "A", 1: "B", 2: "C", 3: "D"}
# for key in d:
# print(key)
#
# for key in d.keys():
# print(key)
"""
Nested for loop: A loop contains another loop is known as nested loop.
Ex: we can write a for loop inside another loop such loops are nested for loop.
Here outer loop indicates no.of rows and inner loop indicates no .of columns.
It is used to display rows and columns formatted data
"""

Author: Boyina Narendra

Supporting Author: M. Meera Sindhu

Request: If you find this information useful, please provide your valuable comments

No comments:

Post a Comment