while
loop in Python repeats a block of code as long as a condition evaluates to True
. Once the condition becomes False
, the loop stops.n
using a while loop.
Output:
Explanation: The loop continues to add i
to sum
until i
reaches 7, at which point the condition i < n
becomes False
and the loop ends.for
loop in Python is used to iterate over a sequence of items, such as a list, tuple, string, or range of numbers. It’s the go-to loop when you know the exact number of times you need to repeat a task.range()
function for numerical iterations.range()
function.
Output:
Explanation: The range(2, 12, 2)
generates numbers starting from 2, up to (but not including) 12, with a step of 2, printing each value of i
.i
.for
loop and a while
loop depends on the situation:for
loop when you know the exact number of iterations (e.g., iterating over a list or a range).while
loop when you don’t know the number of iterations in advance and need to continue until a specific condition is met.while
loop to iterate until a condition is met, a for
loop to iterate through a sequence, or a nested loop for more complex tasks, understanding how to utilize loops is a fundamental skill for any programmer. By choosing the right type of loop and using control statements effectively, you can streamline your code and solve problems more efficiently. Click Here to know more our program!