You are on page 1of 6

LOOPS IN PYTHON

1. FOR LOOP :
In a for loop, we will know in advance how many times the loop will need to
iterate because we will be working on a collection with a predefined length.

for < temporary variable > in < collection >:


action statement

The collection is a data type file it can be a string, list, or dictionary.


The temporary variable is everything in the collection that we need to iterate through.
Note that the loop requires colons at the end.
The action statement is written with some space in the next line (indentation).

Example :
let’s consider a list of sports items:
sports_items = [‘football’,’ cricket bat’,’ baseball’,’ handball’,’ hockey’]

If we want to print every element in it, we simply use the code:

for items in sports_items:


print(items)

# Here we created a temporary variable named items and that item includes every item
in the list and then we print that item.

Note: If we want something to be printed multiple times we use for loop with range.

multiple_times = “ Print this statement multiple times”


we will use :

for words in range(5) times # temporary word doesn’t matter but it needs be
print (multiple_times) something means to print in 5 times
2. WHILE LOOPS :

A while loop performs a set of instructions as long as a given condition is


true.

while < Conditional statement > :


Action statement

Let’s consider a simple while loop :

count = 0
while count <= 3 :
print(“count”)
Countdown += 1

Let’s break the loop down:

 Count is initially defined with the value of 0. The conditional statement in the while loop
is count <= 3, which is true at the initial iteration of the loop, so the loop body executes.

o Inside the loop body, the count is printed and then incremented by 1.

 When the first iteration of the loop has finished, Python returns to the top of the loop
and checks the conditional again. After the first iteration, the count would be equal to
1 so the conditional still evaluates to True and so the loop continues.

 This continues until the count variable becomes 4. At that point, when the conditional is
tested it will no longer be True and the loop will stop.
3. LOOP CONTROL :

Loops in Python are very versatile. Python provides a set of


control statements that we can use to get even more control out
of our loops.

I. BREAK

When the program hits a break statement it immediately terminates


a loop. It is used to find an item in a list and can have multiple uses
as well.

break requires another if/elif/else condition. If that condition inside


a loop is fulfilled the loop will immediately terminate.

II. CONTINUE

We have used the break to end the loop when the condition is
fulfilled in other situations like where we don’t want to end the loop
entirely and just skip that particular iteration we use to continue.

It is also used with a conditional statement.

let’s consider,
x = [ -3,2,3,4,2,4,-6,-4,-2,-1,-5]
we only want to print positive integers, we will code :

For numbers in x:
if numbers >= 0:
continue
print(numbers)
4. NESTED LOOPS :

Loops within a loop are called ‘Nested Loop’. Loops can be nested in
Python, as they can with other programming languages. We will find certain
situations that require nested loops.
They are used to print 2D-Lists.

Consider this example :


project_teams = [["Ava", "Samantha", "James"], ["Lucille", "Zed"], ["Edgar",
"Gabriel"]]

Here we want to print all members of the team irrespective of their team. So the first
loop will go through the team and then the other nested loop will go through the
members.

For teams in project_teams # teams = temporary variable of the primary list.


For members in teams: #members = temporary variable of sec. list
Print(members)

5. LIST COMPREHENSIONS :

In coding, it is preferred to use shorter and more comprehensive codes as a


professional.

I. LIST COMPREHENSIONS WITHOUT CONDITION :

Consider the following example where want a new list with double the constants of
list 1. So we will write a code that is:

numbers = [2, -1, 79, 33, -45]


doubled = []

for number in numbers:


doubled.append(number * 2)
#using the append method to add the values in the list.
print(doubled)

Comprehensive loop statement of the example.


The objection at the previous page will also be achieved as:

numbers = [2, -1, 79, 33, -45]


doubled = [num * 2 for num in numbers]
# the condition of the loop is written before the start of the loop. Written in [ ] so it is
considered a list.

print(doubled)

II. LIST COMPREHENSION WITH CONDITION :


Comprehensions in code can also be achieved with conditional statements.

Consider the example of a loop that is comprehensively written:


numbers = [2, -1, 79, 33, -45]
only_negative_doubled = []
for num in numbers:
if num < 0:
only_negative_doubled.append(num * 2)
print(only_negative_doubled)

This code can be written comprehensively using the following code:

numbers = [2,-1,79,33,-45]
only_negative_doubled = [ num * 2 for num in numbers if num < 0]
# conditional statement is written after the loop statement.

We can conclude the comprehensive loop topic using the following formula:
<action statement> for <temporary variable> in <list>
<conitional statement>.

You might also like