In this tutorial, you will learn about while loop in python and how to use it with some code samples.
Loops are statements that run until a certain condition is reached. Python supports the following loops.
Similar to other programming languages, the while loop in python runs a specified time until the condition is met, once reached the line immediately to the while loop is executed.
Syntax:
while expression: statement(s)
Inside the while loop, you can have other conditional statements like if, if-else and nested if.
Now let’s see a simple program using while loop in python
Input:
a=57 while(a<65): print(“Using while loop we get:”, a) a=a+1 print(“while loop has reached the condition”)
Output:
Using while loop we get: 57 Using while loop we get: 58 Using while loop we get: 59 Using while loop we get: 60 Using while loop we get: 61 Using while loop we get: 62 Using while loop we get: 63 Using while loop we get: 64 while loop has reached the condition
Now let’s see a simple program using a while loop with a conditional statement in python
Input:
i = 0 a = 'Developerpublish academy' while i < len(a): if a[i] == 'y': i += 1 break print('Following letter :', a[i]) i += 1
Output:
Following letter : D Following letter : e Following letter : v Following letter : e Following letter : l Following letter : o Following letter : p Following letter : e Following letter : r Following letter : p Following letter : u Following letter : b Following letter : l Following letter : i Following letter : s Following letter : h Following letter : Following letter : a Following letter : c Following letter : a Following letter : d Following letter : e Following letter : m
Simple program using while loop with conditional statement else in python
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1226′,’_blank’)”]
a = 57 while a < 60: print(a) a += 1 else: print("Value of a has exceeded 60 ")
Output:
57 58 59 Value of a has exceeded 60