Professional Documents
Culture Documents
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.
Example :
let’s consider a list of sports items:
sports_items = [‘football’,’ cricket bat’,’ baseball’,’ handball’,’ hockey’]
# 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.
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 :
count = 0
while count <= 3 :
print(“count”)
Countdown += 1
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 :
I. BREAK
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.
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.
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.
5. LIST COMPREHENSIONS :
Consider the following example where want a new list with double the constants of
list 1. So we will write a code that is:
print(doubled)
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>.