|
|
| Introduction | Variables | If-else |
| Strings | Functions | while-loop |
| For-Loop | List | Set |
| Dictionary | Tuple | Try..Except |
| Class/Object | Inheritance | Polymorphism |
| File Handling | ||
While loops in Python are very useful if you need to execute some statements inside the loop while certain condition remains valid. The structure of while loop is as follows:
while condition is true:
execute some statements;
So, we can say the while loop executes lines of code repeatedly, given condition still holds true. Most of the time when we use a while loop, we have to declare a variable as a loop counter. The condition in the while
statement will evaluate the value of counter to check if it is smaller or greater than a certain value. We need to be very careful when using the while because it could easily get into an infinite loop due to any improper
code. Let's see some examples of while loops.
Code Example 1:
#Print the numbers from 1 to 10..
number = 1
while number <= 10 :
print(number)
number = number+1
#Output:
1
2
3
4
5
6
7
8
9
Code Example 2:
#Numbers between 1 and 20, divisible by 3
varNum=1
while varNum <= 20 :
if(varNum%3==0):
print(varNum)
varNum = varNum+1
#Output:
3
6
9
12
15
18
Sometimes it is necessary to break the while loop based on certain conditions. That's where the break is used. With the break statement, you can stop the while loop even if the while condition is true. Let's see an example below.
Code Example 3:
#Exit the loop when counter is 5:
counter = 0
while counter < 10:
print(counter)
if counter == 5:
break
counter=counter+1
#Output:
0
1
2
3
4
A while True loop generates an infinite loop that will be executed indefinitely unless a break statement is encountered. This is used when the exact number of iterations is not known upfront. The loop can be terminated with a break statement, based on a condition. It is used in chatbots to handle continuous user interaction.
Code Example 4:
#In this example, the infinite while loop breaks when the user input's 'quit':
while True:
user_input=input("Enter city name. Enter 'quit' to exit:")
if user_input == 'quit':
print("Good Bye!")
break
print(f"You entered: {user_input}")
print("Loop finished.")
#Output:
Enter the name of the city you visited. Enter 'quit' to exit: Chicago
You entered: Chicago
Enter the name of the city you visited. Enter 'quit' to exit: Dallas
You entered: Dallas
Enter the name of the city you visited. Enter 'quit' to exit: quit
Good Bye!
Loop finished.
When you use a continue statement in a while loop, you can stop the current iteration, and move to the next iteration.
Code Example 5: #The following code demonstrates
#the use of continue in
#While loop. counter = 0 while counter < 5: counter=counter+1 if counter == 3: continue print(counter) #Output: 1 2 4 5
The else block is executed with the while statement to execute a block of code once when the while condition is not true anymore. This else gets executed only if the while loop ends naturally. It will not be executed if the while loop ends through the break statement.
Code Example 6:
#The following illustrates how else works in the while loop.
counter = 0
while counter < 5:
print(f"The counter is: {counter}")
count += 1
else:
print("The while-loop finished naturally.")
#Output:
Inside the loop: 0
Inside the loop: 1
Inside the loop: 2
Inside the loop: 3
Inside the loop: 4
The loop finished naturally.