DEV Community

Gowtham
Gowtham

Posted on

Python - for & while Loops

for Loop

For loops is used to iterate over a sequence such as a list, tuple, string or range. It executes a block of code once for each item in the sequence.

n = 4
for i in range(0, n):
print(i)

Output

0
1
2
3

Explanation:

  • n = 4 stores the ending value for the loop.
  • range(0, n) generates numbers from 0 to 3.
  • for i in range(0, n): iterates through each number in the range.

A for loop can also iterate through sequence elements using their index values with the help of range() and len().

a = ["need", "for", "speed"]
for idx in range(len(a)):
print(a[idx])

Output

need
for
speed

Explanation:

  • len(a) returns the total number of elements in the list.
  • range(len(a)) generates index values from 0 to 2.
  • a[idx] accesses list elements using their index.

while Loop

While loop repeatedly executes a block of code as long as the given condition remains true. When the condition becomes false, the line immediately after the loop in the program is executed.

cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Gowtham")

Output

Hello Gowtham
Hello Gowtham
Hello Gowtham

Explanation:

  • cnt = 0 initializes the counter variable.
  • while (cnt < 3): runs the loop while the condition is true.
  • cnt = cnt + 1 increases the counter value by 1.

Infinite While Loop

An infinite while loop runs continuously because its condition always remains true.

while (True):
print("Hello Gowtham")

Explanation:

  • while(True): creates a loop with a condition that is always true.
  • print("Hello Gowtham") keeps executing repeatedly inside the loop.

Top comments (0)