Python while Keyword



The Python while keyword used to create a while loop. The loop executes a block of code until a give condition is satified. When the given condition is False, it will come out of the loop and the statements which are out of the loop executes.

The while keyword is a case-sensitive keyword. This loop come under indefinite iteration, which means the number of times the loop is executed is not known in advance.

When a while loop is executed, the condition is first evaluated in a Boolean context and if it is True, the loop body is executed, then the condition is checked again, if it is still True then the body is executed again and this condition until the given condition becomes False.

Syntax

Following is the syntax of the Python while keyword −

while condition:
    statement1
    statement2

Example

Following is an example of the Python while keyword −

x=1
while x < 6:
    print(x)
    x=x+1

Output

Following is the output of the above code −

1
2
3
4
5

Using while Keyword in if-else

The while loop is an indefinite iterative loop, to make it definite iterative loop we use if-else along with break statement inside the loop. The condition is evaluated first and if the condition is True control enter inside the loop. if block is executed, if the given condition is True, otherwise else block is executed.

Example

Here, we have created an integer variable and checked whether it is an even number or not. To make the while loop definite we used break statement −

var1 = 28
while True:
    if var1%2==0:
        print(var1,"is a even number")
        break

Output

Following is the output of the above code −

28 is a even number

Using while with the pass Keyword

When we define a while loop without any statements inside the it an IndentationError will occur. To avoid the error we will use pass statement inside it.

Example

Here, is an usage of pass keyword in while loop −

print("Empty loop")
while True:
    pass

Output

Following is the output of the above code −

Empty loop

Using while loop with control statements

The break and continue are the control statements used to control the loop flow. The break statement is used to exist the while loop. When the break is encountered, the loop stops immediately, and the program continues with next statements after the loop. The continue statement is used to skip a particular condition and rest of the code in that iteration and move to next iteration.

Example

Here, is the usage of the control statements in the while loop −

i = 0
while i < 10:
    i = i + 1
    if i == 5:
        break  # Exit the loop when i is 5
    elif i % 2 == 0:
        continue  # Skip the rest of the loop if i is even
    else:
        print(i)

print("Loop ended")

Output

Following is the output of the above code −

1
3
Loop ended
python_keywords.htm
Advertisements