While Loop
Introduction:
- A while loop in Python is used to execute a set of statements repeatedly based on the result of a boolean condition.
- The while loop is one of the looping statements in Python.
Syntax:
python
while condition:
statement(s)
whileis a Python keyword,conditionis a boolean expression, andstatement(s)is a block of code.- The statement(s) inside the while loop must be indented.
Examples:
- Print 1 to N Using While Loop:
This example uses a while loop to print numbers from 1 to 4.
pythonn = 4 i = 1 while i <= n: print(i) i += 1Output:
1 2 3 4- Explanation: The variable
iis incremented in each iteration until it reaches the value ofn, at which point the loop condition becomes false.
- Break While Loop:
This example breaks the while loop prematurely using the
breakkeyword.pythona = 4 i = 0 while i < a: print(i) i += 1 if i > 1: breakOutput:
0 1- Explanation: The loop breaks when
ibecomes 2, as the conditioni > 1is met.
- While Loop with Continue Statement:
This example skips an iteration of the while loop using the
continuekeyword.pythona = 4 i = 0 while i < a: if i == 2: i += 1 continue print(i) i += 1Output:
0 1 3- Explanation: The loop skips printing the value 2 and continues with the next iteration.
Exercises:
- Print Even Numbers Using While Loop:
Write a program to print even numbers from 1 to 10 using a while loop.
pythoni = 1 while i <= 10: if i % 2 == 0: print(i) i += 1
- Use Break in While Loop:
Write a program to print numbers from 1 to 5 using a while loop. Break the loop if the number is 3.
pythoni = 1 while i <= 5: if i == 3: break print(i) i += 1
- Use Continue in While Loop:
Write a program to print numbers from 1 to 10 using a while loop. Skip the number 5.
pythoni = 1 while i <= 10: if i == 5: i += 1 continue print(i) i += 1
Summary:
- In this tutorial, we learned how to write a while loop in a Python program, and how to use
breakandcontinuestatements with a while loop. Practice these examples to become proficient in using while loops in your Python programs!