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…
For loops in Python allow you to iterate over a sequence, such as a list, tuple, string, or range. This means the code within the loop will run once for each item in the sequence. For example, the code n = 4 for i in range(0, n): print(i) will output 0, 1, 2, and 3. Here, n = 4 sets the ending value for the loop. range(0, n) generates numbers from 0 to 3. The for loop then iterates through each number in this range.
A for loop can also iterate through elements of a sequence (like a list) using their index values. For instance, if a = [need, for, speed], the code for idx in range(len(a)): print(a[idx]) will print 'need', 'for', and 'speed'. The len(a) function returns the total number of elements in the list, and range(len(a)) generates index values from 0 to 2. The a[idx] syntax accesses list elements using their index.
On the other hand, while loops in Python repeatedly execute a block of code as long as a certain condition remains true. Once the condition becomes false, the program continues with the line immediately following the loop. For example, the code cnt = 0 while (cnt < 3): cnt = cnt + 1 print('Hello Gowtham') will print 'Hello Gowtham' three times.
Here, cnt = 0 initializes a counter variable. The while (cnt < 3) condition checks if the counter is less than 3. If true, the loop runs, and cnt = cnt + 1 increments the counter by 1. If the condition is false (when cnt equals 3), the program skips the loop and proceeds to the next line.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.