Python Loop Statements

 

2 Types of loops in python:


1) For Loop:

It is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python.

string = "Python"

# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)

----------------------------------------------------------------------------------------------------------------------------

numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]

# initializing a variable that will store the sum
sum_ = 0

# using for loop to iterate over the list
for num in numbers:

sum_ = sum_ + num ** 2

print("The sum of squares is: ", sum_)

-----------------------------------------------------------------------------------------------------------------------------

my_list = [3, 5, 6, 8, 4]
for iter_var in range( len( my_list ) ):
my_list.append(my_list[iter_var] + 2)
print( my_list )  

-----------------------------------------------------------------------------------------------------------------------------

for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string) 

 
2) While Loop:

While loops are used in Python to iterate until a specified condition is met.

counter = 0

# Iterating through the while loop
while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
# Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")

-----------------------------------------------------------------------------------------------------------------------------

i = 1

# using the while loop to find numbers between 1 to 50 that are divisible by 5 or 7
while i < 50:
if i % 5 == 0 or i % 7 == 0:
print(i, end=' ')
i += 1

-----------------------------------------------------------------------------------------------------------------------------

num = 21
counter = 1
# We will use a while loop for iterating 10 times for the multiplication table
print("The Multiplication Table of: ", num)
while counter <= 10: # specifying the condition
ans = num * counter
print (num, 'x', counter, '=', ans)
counter += 1 # expression to increment the counter  

 

   

Comments

Popular posts from this blog

How to Run Python in MS Visual Studio Code

Python Strings