Python Basics

Certification Training
3669 Learners
View Course Now!

Python Loops Tutorial

Welcome to lesson four of the Python basics tutorial which is a part of the Python Basics Course offered by Simplilearn. This lesson will provide detailed information on loops.

Objectives

After completing this lesson on Python Loops, you will be able to:

  • Define loops and their types in python

  • Describe the range function

  • Explain the break and continue statements in a loop.

Loops in Python

In general, statements are executed sequentially. The first statement in a code is executed first, followed by the second one, and so on. There may be a situation when you need to execute a block of code several times.

Programming languages provide various control structures that allow far more complicated execution paths. A loop statement allows executing a statement or a group of statements multiple times.

Python provides this facility using three types of loops:

  • for loop

  • while loop

  • nested loop

Before looking into loops in detail, it's important to know about the Range function in Python.

Range Function

In Python, the range function is normally used with loop statements.

Example:

>>> range(5)

[0,1, 2, 3, 4 ]

As mentioned in the given example, if you call this function with a number value, python will return you a list of values ranging from zero to that number minus one. In the highlighted example, since a value of five has been passed to the range function, it has returned a list containing values from zero to four.

For Loop

For loops is a way to repeat an action again and again. To understand it better, see the example below:

for x in range(10):

print x

For x in range 10, it will execute the statement given inside the for block ten times.

As discussed earlier, the range function, in this case, will return a list of numbers from one to ten and those numbers will be assigned to the x variable one at a time.

Therefore, in this case, Python will print the current value inside the x variable. So it will print values from one to ten on the screen.

Let us consider one more example as shown below.

fruits = ['apple' , 'mango' , 'orange' , 'banana']

for fruit in fruits:

print fruit

Remember, a list can be a list of strings too. In the given example, a list of fruits has been created. Now for every value in this list, you can execute a set of statements using the for loop. In the mentioned example, you will be able to print the names of the fruit, as declared above, for every value in the given list.

While Loop

To understand while loops, see the example below.

Example:

x = 0

while x <= 100:

print x

x = x+1

A variable ‘x’ has been created here with an assigned value of zero.

While the value of x is less than or equal to 100, it will keep performing the steps inside the while loop.

Inside this while loop, you can print the value of x and then instrument the value by one. This code will print all values from 0 to 100.

You can see the syntax of the while loop above, which is very much like the English language (while a condition is true, do this).

Nested Loop

While creating iterative programs, you may come across many situations where you will need to add a loop inside a loop. These are called nested loops. You can add a while loop in a for loop, and vice versa.

Similarly, you can also add a while loop inside another while loop, or a for loop in an existing for loop.

See the given example to understand the usage of nested loops.

i = 2

while(i < 100):

j = 2

while(j <= (i / j)):

if not(i % j): break

j = j + 1

if (j > i / j): print i, " is prime"

i = i + 1

In the highlighted code, you need to find out prime numbers less than 100. For this, a while loop with the variable ‘i’ has been created to iterate till 100. Inside this while loop, one more loop has been created, which checks if the current number is divisible with any lesser number or not.

If the current number is not divisible, then it prints i is prime.

Break Statements

Sometimes you don't know when to end the loop until you get halfway through the body. In such a case, you can use the break statement to jump out of the loop.

Break statements are normally used with the if condition inside loops. A condition is checked in the loop for all iterations of loops. When that condition meets, a break statement is executed.

The execution of a break statement will end the loop, and the code written after the loop will start executing. Note that if you write ‘while True’, it becomes an infinite loop, since the condition is always true. Remember, break statements help to come out of such infinite loops.

Suppose that you want to keep the while loop running until the value in the x variable is less than 20 and keep on printing the value. In this case, you can write the code as shown below.

Example:

x = 1

while True:

print x

x = x+1

if x > 20:

break

Continue Statement

Continue statement is also a very important keyword. It's used to skip a specific iteration during a loop execution. See the example shown below and imagine that you want to print all the odd numbers from 0 to 100.

Example:

for x in range(100):

if (x % 2) == 0:

continue

print x

In such a situation, you can write a while loop. Inside this while loop, you can check whether the current number is even or not by dividing it by 2, using the if condition.

If that number is even, you can call the continue statement as shown in the example. Otherwise, print the number. This is how you can skip the execution of a specific iteration in some situations.

Summary

Let's summarize the topics covered in this lesson.

  • A loop statement can execute a statement or a group of statements many times.

  • Three types of loops are used in python for loop, while loop, and the nested loop.

  • The break statement exits the control from a loop.

  • The continue statement helps in skipping, an iteration.

Conclusion

With this, we have come to an end of this lesson on Python Loops.

  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*