Oct 8, 2024
Welcome to the Python Loops Tutorial by SimplyLearn. In this session, we covered the fundamentals of loops in Python, focusing on different types of loops and their applications.
for iterator_variable in sequence:
# statements
Iterating over a string:
s = "simply learn"
for i in s:
print(i)
Using the end
parameter in print
:
end
parameter.for i in s:
print(i, end="*")
Iterating over a list:
programming = ["Java", "Python", "Ruby", "HTML"]
for iter in programming:
print(iter)
Finding the average of numbers:
list_num = [20, 25, 10, 50, 45]
sum = 0
for i in list_num:
sum += i
average = sum / len(list_num)
Using range()
function:
for i in range(1, 10):
print(i)
Iterates from 1 to 9.
With step:
for i in range(0, 10, 2):
print(i)
Nested For Loops:
companies = ["Google", "Apple", "PWC", "Uber"]
for i in companies:
for letter in i:
print(letter)
For loop with else clause:
for i in range(0, 10, 3):
print(i)
else:
print("The loop has completed execution")
Using break
and continue
:
break
: Exit the loop before completing all iterations.continue
: Skip the current iteration and move to the next.while expression:
# statements
Basic While Loop:
i = 0
while i < 10:
i += 1
print(i)
Using break
and continue
:
break
.continue
.Using else
with While Loop:
i = 1
while i < 5:
print(i)
i += 1
else:
print("i is not less than 5")
List operations using While Loop:
a = [1, 2, 3, 4, 5]
while a:
print(a.pop())
Printing patterns:
for i in range(11):
for j in range(i):
print("*", end=" ")
print()
Multiplying elements of two lists:
list1 = [2, 4, 6]
list2 = [2, 4, 6]
for i in list1:
for j in list2:
if i == j:
continue
print(i, "*", j, "=", i * j)
Checking perfect numbers:
a = 1
while a <= 100:
sum = 0
for i in range(1, a):
if a % i == 0:
sum += i
if sum == a:
print("Perfect number:", a)
a += 1
Perfect number between 1 and 100 are 6 and 28.
These loops help in iterating over data structures in Python to perform repeated tasks efficiently. Understanding loops is crucial for writing efficient and effective Python code.