in , ,

Python while Loop

Loops are used in programming to rehash a particular block of code. In this article, you will learn to create a while loop in Python.

What is while loop in Python?

The while loop in Python is used to repeat over a square of code as long as the test articulation (condition) is true.

We generally use this loop when we don’t know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:
    Body of while

In the while loop, the test expression is checked first. The body of the circle is entered just if the test_expression assesses to True. After one cycle, the test expression is checked once more. This procedure proceeds until the test_expression assesses to False.

In Python, the body of the while circle is resolved through space.

The body begins with space and the first unindented line marks the end.

Python interprets any non-zero value as TrueNone and 0 are interpreted as False.

Flowchart of while Loop

Flowchart of while Loop

Example: Python while Loop

# Program to add natural
# numbers up to 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)
When you run the program, the output will be:
Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter factor I is less than or equal to n (10 in our program).

We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).

Finally, the result is displayed.


While loop with else

Same as with for loops, while loops can also have an optional else block.

The else part is executed if the condition in the while circle assesses to False.

The while loop can be ended with a break statement. In such cases, the else part is disregarded. Henceforth, some time circle’s else part runs if no break happens and the condition is false.

Here is an example to illustrate this.

'''Example to illustrate
the use of else statement
with the while loop'''

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside the loop three times.

On the fourth iteration, the condition  while becomes False. Hence, the else part is executed.


Please feel free to give your comment if you face any difficulty here.

For More Latest Articles Click on Below Link

salman khan

Written by worldofitech

Leave a Reply

Python for Loop

Python break and continue