What is While Loop - How and when to use it.
What are why loops and how to use them viteac.blogspot.com |
While Loop iterates over block of code until specific condition is met in other words some block of code is repeated until condition is True.
Example 1:
Print text: "While loop prints" and count.
count = 0
while count < 5:
count += 1
print('While loop prints', count)
#output:
While loop prints 1
While loop prints 2
While loop prints 3
While loop prints 4
While loop prints 5
Process finished with exit code 0
Count = 0 is a variable with defined value "0" which we use to count repeated loop.
Now we have block of code in while loop statement to execute:
while count < 5 defines condition which in that case is: till count is less than 5: do something.
count += 1 : count with every loop takes new value increased about 1.
print('While loop prints', count) with every loop print "While loop prints" + current value of variable "count".
Example 2:
Print text till user enters: Q
text = 'Hello World'
printing = False
while printing != True:
printing = input('Press ENTER to print text or press Q to quit. ')
if printing in ['Q', 'q']:
printing = True
else:
print( 'Loop prints:', text)
In this example we define variable text which contains text to print : "Hello World"
Variable printing is defined as False
While loop takes condition: "till printing is not True: do something"
Then if statements checks the user input, if user entered "Q" or "q" the printing variable is True what means while loop breaks otherwise loop goes to else statement which prints text.
Example 3 Infinite while loop:
Infinite loop runs infinitely while condition is True. To create infinite loop use while True:
while True:
print('Infinite loop')
__________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Infinitive loop
Infinitive loop
Infinitive loop
Infinitive loop
Infinitive loop
Infinitive loop
Infinitive loop
The print statement will be executed endless time.
You can break and stop running infinite loop with some condition.
while True:
num = int(input('Enter the number: '))
if num == 0:
break
__________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Enter the number: 1
Enter the number: 2
Enter the number: 3
Enter the number: 4
Enter the number: 5
Enter the number: 6
Enter the number: 7
Enter the number: 8
Enter the number: 9
Enter the number: 0
Above user is asked to enter a number endless time, the loop will be broken under one condition: user enters 0.
Read also:
- How to check if user user input is Empty
- Prevent fro crashing program when user enters no integer
- User Enters no integer - how to prevent program from crashing.
Comments
Post a Comment