Understanding Loops or Types of Loops for loop while loop

 Understanding Loops

Understanding Loops or Types of Loops for loop while loop pro in python
loop in python

Whenever you see a repetitive pattern in code, and there's a collection

Types of Loops

Understanding Loops or Types of Loops for loop while loop pro in python
types of loop in python

There are mainly two types of loops in Python:

  • for loops: Commonly used with lists and used when the repetition count is known.
  • while loops: Commonly used when repetition is based on a condition and we don't know the exact repetition count.
of items, it's a clear sign that a "for loop" could be used to simplify the
task. Let's understand the syntax of "for" loop.

syntax : for item in list_of_items:

for loop :

  • LOOP THROUGH A LIST

example code : 
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits: 
    print(fruit)

Output :
apple
banana
cherry

  • USING range() WITH for LOOP :

for i in range(5):
    print(i)

Output :
0
1
2
3
4

  • LOOP THROUGH A STRING :
for char in "python":
    print(char)

Output :
p
y
t
h
o
n

  • LOOP WITH break AND continue :
#break
for num in range(10):
    if num==5:
      break
    print(num)
Output :
0
1
2
3
4

#continue
for num in range(10):
    if num == 5:
        continue
    print(num)
Output:
0
1
2
3
4
6
7
8
9

LOOP WITH else block

for i in range(3):
    print("Looping",i)
else:
    print("Loop finishing")
Output:

Looping 0
Looping 1
Looping 2
Loop finishing

while loop :
while condition:
#code to execute 
break to exit 
i = 0
while i < 5:
    print(i)
    i += 1

Output 
0
1
2
3
4
continue to skip irretation
i = 0
while True:
    print(i)
    i += 1
    if i == 3:
        break
Output:

1
2

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5
while loop with else
i = 1
while i <= 3:
    print(i)
    i += 1
else:
    print("Loop completed!")
Output:

1
2
3
Loop completed!
  • You have to must try in your python compiler use idle avoid online compilers to Errors

Post a Comment

0 Comments