Free Web Development Online Tutorials, Learn to Code
loops in Python, Python loops example, write different loops in python, break in for loop

Python Loops Examples

In this python loop tutorial you will learn how to write different type of loops in python.

What is loop?

Loop is basically a repetitive process of doing same thing based on some predefine conditions, that means some piece of code will be executed again and again.

Like other programming languages, there are different types of loop in python.

For loop example with string array

In this example below you can see how to loop through string array variable using for loop

def getCountries(self):
        countries = ["India", "USA", "UK", "Canada", "UAE"];
        for c in countries:
            print(c)

For loop example with string

This is an example of looping through a string and printing each character.

def getLetters(self):
    string = "this is a for loop example";
    for c in string:
        print(c)

break in for loop example

This is how you can use break in for loop, we want to exit the loop when our if condition is satisfied

countries = ["India", "USA", "UK", "Canada", "Australia"];
for c in countries:
    print(c)
    if c == "UK":
        break

continue in for loop example

Using continue statement we can stop looping the current iteration, and continue to move next. continue statement can be very useful when you have multiple statement or function to be executed in each loop, for any specific condition we can skip to next, without executing any other function inside .

countries = ["India", "USA", "UK", "Canada", "Australia"];
    for c in countries:
    print(c)
    if c == "UK":
        continue

While Loop in Python Example

While loop in python is very similar to if statement, we also can use while with else statement, like the way we write if and else, we can also write while and else.

    While (condition):
	    Keep working
count = 0
while (count <= 4):     
    count = count + 1
    print("count value :", count)

We also can use else statement with while loop, like when condition is satisfied if there is any function to be executed.

count = 0
while (count <= 4):     
    count = count + 1
    print("count value :", count)
else :
    print("i have to enter now")

Look at above code, using else statement like the way we write if else.

Nest Loop Example

countries = ["India", "USA", "UK", "Canada"];
types = ["Good", "Very Good", "Not Good"];
for c in countries:
    for t in types:
        print(c, t)

Range() Function in Loop Python example

In python we can loop through any range, here is an example of using range function

    for c in range(4):
        print(c)

There are different overloads in range function, range(start, stop, step=optional)

   for c in range(2,8,2):
        print(c)
Comment
Name
Email
Website
Subscribe
 
Python loops

Loops in Python
Python programming examples | Join Python Course