DEV Community

Punitha
Punitha

Posted on

While and For Loop Concepts

What is a While Loop?

  • A while loop executes a block of code as long as a specified condition is True.

Syntax:

while condition:
    <statement>
Enter fullscreen mode Exit fullscreen mode

Example:

i = 1
while i <= 5:
    print(i)
    i = i + 1
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

What is a For Loop?

  • A for loop is used to execute a block of code repeatedly for a sequence of values.

Syntax:

range(start, stop, step)
Enter fullscreen mode Exit fullscreen mode

Parameters:

  • start -> Starting value(included)

  • stop -> Ending value(not included)

  • step -> Increment or decrement value

Syntax:

for variable in sequence:
    <statement>
Enter fullscreen mode Exit fullscreen mode

Example:

for i in range(1,6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Difference between for loop and while loop:

For Loop:

  • Used when the number of iterations is known.

  • Iterates over a sequence.

  • Easier to use for fixed repetitions.

While Loop:

  • Used when the number of iterations is unknown.

  • Runs based on a condition.

  • Suitable for condition-based repetitions.

Top comments (0)