Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

While Loops in Python

While Loops in Python

While Loops in Python

A while loop in Python allows you to repeatedly execute a block of code as long as a given condition is True. This type of loop is useful when you want to repeat an operation multiple times without knowing in advance how many iterations are needed.


Syntax of a While Loop:

while condition:    # Code block to be executed
  • The condition is evaluated before each iteration of the loop.

  • If the condition evaluates to True, the code inside the loop is executed.

  • The loop continues to execute as long as the condition remains True.

  • If the condition evaluates to False, the loop terminates, and the program continues with the code after the loop.


1. Basic While Loop Example

Example:

count = 1while count <= 5:    print("Count is:", count)    count += 1

Output:

Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5
  • The loop runs while count is less than or equal to 5, and the value of count increases by 1 after each iteration.


2. Infinite While Loop

If the condition of the while loop is always True, the loop will run indefinitely (i.e., an infinite loop).

Example of Infinite Loop:

while True:    print("This will run forever!")    break  # To stop the infinite loop
  • Here, the loop would run indefinitely unless there's a way to break out of it. In this case, the break statement is used to stop the loop after one iteration.


3. Using break to Exit the Loop

The break statement is used to exit the loop prematurely when a certain condition is met, even if the loop condition is still True.

Example:

count = 0while count < 10:    if count == 5:        break  # Exit the loop when count is 5    print(count)    count += 1

Output:

01234
  • The loop stops when count reaches 5 due to the break statement.


4. Using continue to Skip an Iteration

The continue statement is used to skip the current iteration and move to the next one without executing the remaining code inside the loop.

Example:

count = 0while count < 10:    count += 1    if count == 5:        continue  # Skip printing when count is 5    print(count)

Output:

1234678910
  • When count is 5, the continue statement skips the print and goes back to the top of the loop.


5. While Loop with Else

A while loop can also have an else block, which is executed when the loop condition becomes False. The else block is not executed if the loop is terminated using a break.

Example:

count = 1while count <= 5:    print("Count is:", count)    count += 1else:    print("Loop has ended.")

Output:

Count is: 1Count is: 2Count is: 3Count is: 4Count is: 5Loop has ended.
  • The else block is executed after the loop finishes, but it will not execute if the loop is exited via break.


6. Nested While Loops

You can have a while loop inside another while loop. This is known as a nested loop.

Example:

i = 1while i <= 3:    j = 1    while j <= 2:        print(f"i = {i}, j = {j}")        j += 1    i += 1

Output:

i = 1, j = 1i = 1, j = 2i = 2, j = 1i = 2, j = 2i = 3, j = 1i = 3, j = 2
  • Here, for each value of i, the inner while loop runs for j values from 1 to 2.


7. Practical Example:

A practical example of a while loop is when asking the user to input a valid value until the user provides the correct input.

Example:

while True:    user_input = input("Enter a number between 1 and 10: ")    if user_input.isdigit():        number = int(user_input)        if 1 <= number <= 10:            print(f"Valid number: {number}")            break        else:            print("The number must be between 1 and 10.")    else:        print("Please enter a valid number.")
  • This loop keeps asking the user for a number until a valid number between 1 and 10 is provided.


8. Conclusion

  • while loops are used to execute a block of code repeatedly as long as a specified condition is True.

  • They are useful when you don't know beforehand how many times you need to repeat a task.

  • You can control the flow of a while loop with statements like break, continue, and else.

  • It's important to ensure that the loop condition eventually becomes False to prevent infinite loops, unless intentionally required.

Understanding how to use while loops effectively can significantly improve the flexibility of your Python programs.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql