python iteration | while loop | for loop with examples

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
We mainly use loops for repeating the same code or function several numbers of times.

Types of Loop

There are the 2 types of loops in Python.

for loop

for loop used to iterating over a sequence.
syntax:

for item in sequence:
       your_code(item)

we can use ‘else‘ statement with both ‘while‘ and ‘for‘ loop
EXAMPLE:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 10:01:56 2021
@author: mycloudplace
"""
def main():
    name = "prem"
    for s in name:
        print(s, end=" ")
    else:
        print("")
        print("outside of for loop")
    print("Using range function to print sequence")   
    for i in range(2,22,2):
        print(i, end=" ")
        
if __name__ == "__main__":
    main() 

OUTPUT:

p r e m 
outside of for loop
Using range function to print sequence
2 4 6 8 10 12 14 16 18 20 

Go to top (Types of Loop)


while loop

while loop keep executing a block of code until the given condition true.

EXAMPLE:  Printing the multiplication table using both ‘for’ and ‘while’ loop.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 10:01:56 2021
@author: mycloudplace
"""
def main():
    table_list = [11,12,13,14,15] 
    print("Below are the Multiplication Table by using 'while' and 'for' loop") 
    i=1
    while (i <= 10):
        for num in table_list:
            print((num * i), end="\t")
        print("")
        i+=1   
if __name__ == "__main__":
    main() 

OUTPUT:

Below are the Multiplication Table by using 'while' and 'for' loop
11	12	13	14	15	
22	24	26	28	30	
33	36	39	42	45	
44	48	52	56	60	
55	60	65	70	75	
66	72	78	84	90	
77	84	91	98	105	
88	96	104	112	120	
99	108	117	126	135	
110	120	130	140	150

Go to top (Types of Loop)


‘break’ and ‘continue’ Statements

break statement is used to breaks out of the innermost for or while loop.

continues statement is used to continues with the next iteration of the loop.

EXAMPLE:  Finding the first n (can be any positive integer) prime numbers.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 10:01:56 2021
@author: mycloudplace
"""
def main():
    prime_number_count = 50
    print("First " + str(prime_number_count) + " prime numbers")
    prime_numbers = [] #empty list of prime numbers
    num = 2
    while (len(prime_numbers) <= prime_number_count):
        is_prime = True
        for x in range(2, num):
            if (num % x == 0):
                is_prime = False;
                break;                
        if is_prime:
            prime_numbers.append(num)
        num+=1
    print(prime_numbers)
            
if __name__ == "__main__":
    main() 

OUTPUT:

First 50 prime numbers
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233]

Go to top (Types of Loop)

Our Previous articles

http://mycloudplace.com/python-data-types-with-examples/

Python – installation indentation variable comments

Python Programming Introduction

Python Office Site : https://docs.python.org/3/tutorial/index.html

39 thoughts on “python iteration | while loop | for loop with examples”

  1. Good day! This post could not be written any better!
    Reading this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this article to
    him. Pretty sure he will have a good read.
    Many thanks for sharing!

  2. Hello There. I found your blog using msn. This is an extremely well written article.

    I’ll make sure to bookmark it and come back to read more of your useful information. Thanks for the post.
    I will certainly return.

  3. Pretty nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed surfing around your weblog posts.
    After all I will be subscribing to your feed and I’m hoping you write again soon!

  4. Have you ever thought about publishing an ebook or guest authoring on other websites?
    I have a blog based upon on the same topics you discuss and would love
    to have you share some stories/information. I know my subscribers would enjoy your work.
    If you’re even remotely interested, feel free to shoot me an email.

  5. Very nice post. I just stumbled upon your weblog and wished to say that I have
    really enjoyed browsing your blog posts. After all I’ll be subscribing to your rss
    feed and I hope you write again soon!

  6. Hey There. I found your blog using msn. That is a really
    neatly written article. I will be sure to bookmark it and return to learn extra of
    your useful info. Thank you for the post. I will certainly comeback.

  7. hi!,I really like your writing so much! share we keep in touch more about your article
    on AOL? I need an expert on this area to resolve my problem.
    Maybe that’s you! Taking a look forward to look you.

  8. Hello to every , because I am truly keen of reading this weblog’s post to be updated on a
    regular basis. It contains fastidious stuff.

  9. What’s up everyone, it’s my first visit at this web page,
    and paragraph is actually fruitful designed for me,
    keep up posting these articles or reviews.

  10. Excellent post. Keep writing such kind of information on your blog.
    Im really impressed by your blog.
    Hi there, You have done an incredible job. I’ll definitely digg it and in my view recommend to my friends.
    I’m confident they will be benefited from this website.

  11. Thanks for the auspicious writeup. It in reality used to be a leisure account it.
    Look advanced to far introduced agreeable from you!
    By the way, how can we keep up a correspondence?

  12. Download joker123 Gaming

    it is best contents, like, will visit this web site everyday because it offers feature contents, thanks

  13. download apk joker123 versi terbaru

    When some one searches for his required thing, thus
    he/she needs to be available that in detail,
    thus that thing is maintained over here.

  14. I just could not leave your website before suggesting
    that I really loved the standard information a person provide for your visitors?
    Is going to be again ceaselessly in order to
    check up on new posts. Thanks for information on python.

  15. Hello, its good paragraph concerning programming language, we all be familiar with this is a great source
    of facts.

  16. Good site you have here.. It’s hard to find high-quality writing like yours nowadays.
    I seriously appreciate people like you! Take care!!

  17. trufa sin sabor

    Hello, I desire to subscribe for this web site to take most up-to-date updates,
    thus where can i do it please assist.

  18. Write more, thats all I have to say. Literally, it seems as though you
    relied on the video to make your point. You obviously know what youre talking about, why throw
    away your intelligence on just posting videos to your weblog when you could be giving us
    something informative to read?

Leave a Comment

Your email address will not be published. Required fields are marked *