Python loop example - loops in python With Examples

In this tutorial you are going to learn about Python Loop Techniques. In previous tutorial we discussed about Python pass statement. If you are interested, you can click this link to read that tutorial.

Python Loop

We learned about Python loop before. But Python’s loop is more flexible than that of other language. We can do more interesting things here. Python’s for loop is versatile. We are going to see some examples about this.

Python Loop over a Sequence

This is a very common example of Python for loop. Suppose we have a sequence of items and we need to traverse the sequence one by one. We can use for loop like this:

The output of the following code will be

Python Loop over a Sequence in Reverse Order

You can also print the previous example int reverse order. To do so, you have to use reversed() function. reversed() function reverse the order of a sequence. Have a look over the following code.

The output will be

Python Loop over a Sequence in Sorted Order

You can also print the previous example int sorted order. To do so, you have to use sorted() function. sorted() function sort the order of a sequence. Have a look over the following code.

The output will be

Enumerate Values and Corresponding Index

You can also enumerate values of a sequence along with their indexes. To do so, you have to use enumerate() function. The following code will help understand the thing.

The output will be

Python Loop

Traversing Two or More Sequences

Using python for loop you can traverse two or more sequences at the same time. For example, in one sequence you have a list of name and in another sequence you have the list of hobbies of the corresponding persons. So you have to print persons’ name along with their hobbies. So the following example will guide you to do this.

The output will be

If you practice more, day by day you will learn many Interesting things about python. That’s all about Python loop example. Hope that you understood well. For any query, please comment below.
#HappyCoding

By admin

Leave a Reply