Python - Loops - While

In Python, there are two main types of loops:

  • for loop: This loop is used when you want to execute a block of code for a fixed number of times. It is typically used when you have a collection of items, such as a list or a tuple, and you want to perform some operation on each item in the collection. The for loop iterates over each item in the collection and executes the code block once for each item.
  • while loop: This loop is used when you want to execute a block of code repeatedly while a certain condition is true. It is typically used when you don't know in advance how many times you need to execute the code block. The while loop continues to execute the code block as long as the condition is true.

In Python, a while loop is used to execute a set of statements repeatedly as long as a condition is true. The syntax of a while loop in Python is as follows:

while condition:
    statement1
    statement2
    ...

The loop begins with the while keyword followed by the condition. The statements inside the loop are indented and will be executed as long as the condition is true. The moment the condition becomes false, the control exits the loop and moves to the next statement after the loop.

Here is an example of a while loop that prints the first 5 natural numbers:

i = 1
while i <= 5:
    print(i)
    i = i + 1

In this example, we initialize the variable i to 1. The while loop checks if i is less than or equal to 5. If it is, the loop prints the value of i and increments it by 1. This process continues until i becomes 6 and the condition becomes false.

num = int(input("Enter a number: "))
fact = 1
i = 1
while i <= num:
    fact *= i
    i += 1
print("Factorial of", num, "is", fact)

In the above example, we take user input for a number and initialize two variables fact and i with the values 1 and 1 respectively. Then we use a while loop and check if the value of i is less than or equal to the input number num. If it's true, we multiply the value of fact with i and increment i by 1. This process is repeated until the condition becomes false, i.e., when i becomes greater than num. Finally, we print the value of fact, which gives us the factorial of the input number.

It is important to note that a while loop can potentially run indefinitely if the condition is never met. This is known as an infinite loop and can cause your program to crash or hang. Therefore, it is important to ensure that the condition in a while loop eventually becomes false.