Skill - ‘while’ statement for looping in python
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
while
statement is used to run code again and again until a specified condition is satisfied.
Using ‘while’ statement to print 10 times
x = 1
while x<=10:
print('{0} - Hello World!'.format(x))
x = x + 1
# this prints
'''
1 - Hello World!
2 - Hello World!
3 - Hello World!
4 - Hello World!
5 - Hello World!
6 - Hello World!
7 - Hello World!
8 - Hello World!
9 - Hello World!
10 - Hello World!
'''
Using ‘break’ to abort while loop
In the example below, we can see that the loop is broken using the break
keyword at 4th iteration
x = 1
while x<=10:
print('{0} - Hello World!'.format(x))
if x==4:
break
x = x + 1
# this prints
'''
1 - Hello World!
2 - Hello World!
3 - Hello World!
4 - Hello World!
'''
Using ‘continue’ to skip iteration
In the example below, we can see that the loop is skipped using the continue
keyword at 4th iteration
x = 0
while x<10:
x = x + 1
if x==4:
continue
else:
print('{0} - Hello World!'.format(x))
# this prints
'''
1 - Hello World!
2 - Hello World!
3 - Hello World!
5 - Hello World!
6 - Hello World!
7 - Hello World!
8 - Hello World!
9 - Hello World!
10 - Hello World!
'''
Video
The video for this post can be found here
Online Interpreter
You can run these codes online at https://www.programiz.com/python-programming/online-compiler/
Comments
Post a Comment