Header Ads Widget

Ticker

6/random

Python While Loops

Python While Loops


In Python, a `while` loop is used to repeatedly execute a block of code as long as a given condition is true. Here's the basic structure along with an example:


Basic Syntax:


```python

while condition:

    # code to be executed as long as the condition is True

```


Example:


```python

count = 0


while count < 5:

    print(f"Count is {count}")

    count += 1

```


In this example, the `while` loop continues to execute the indented block of code as long as the condition `count < 5` is true. The `count += 1` statement increments the value of `count` in each iteration, ensuring that the loop will eventually exit when `count` becomes equal to or greater than 5.


Infinite Loop:


Be cautious to avoid unintentional infinite loops. For example:


```python

# This loop will run indefinitely

while True:

    print("This is an infinite loop!")

```


Using `break` and `continue`:


You can use the `break` statement to exit the loop prematurely and the `continue` statement to skip the rest of the code in the current iteration and move to the next iteration.


```python

count = 0


while count < 10:

    if count == 5:

        break # Exit the loop when count is 5

    print(f"Count is {count}")

    count += 1

```


In this example, the loop will break when `count` reaches 5.


```python

count = 0

while count < 5:

    count += 1

    if count == 3:

        continue # Skip the rest of the code in this iteration when count is 3

    print(f"Count is {count}")

```


In this example, the loop will skip the print statement when `count` is 3.


While loops are powerful tools for repetitive tasks, but it's essential to ensure that the condition will eventually become false to avoid infinite loops.

Post a Comment

0 Comments