# Loops

Summary: Loops are another type (if – elif – else being the other) of flow control mechanism available in any programming language. In this section, we will explore the two basic syntaxes available in Python for loops –loops andforloops.while

### Contents

### while loop

count = 0 while count < 10 : print ( count ) count = count + 1

0 1 2 3 4 5 6 7 8 9

In the previous section (flow control in python) we have seen the elevator example. Let’s enhance it a bit by making it a perpetual program. But before we do that, we have to find a way to get user input

floor = input() print ( "floor enetered = ", floor)

Now, we are good to rewrite the program.

As usual , define the variables and set their initial values.

current_floor = 0 # This is just a starting point user_floor = 0 # This is just a starting point

Now, let’s reprogram the elevator program using while loop.

user_floor = 6 while user_floor != "exit" : difference = user_floor - current_floor if difference < 0 : current_floor = user_floor print ( " Move down ") if difference > 0 : current_floor = user_floor print ( " Move up ") if difference == 0 : current_floor = user_floor print ( " Open door ") user_floor = input() if user_floor != "exit" : user_floor = int(user_floor)

Move up Move down Open door Move up Open door Open door Move down Open door Move up Move up Move down

The syntax for while loop looks like this.

### range function

Range function is a built-in function to generate a sequence of numbers. For example, the following will generate a sequence of numbers from 0 to 10

numbers = range(10)

How do you extract these numbers though ? For that you need some kind of an **iterator**. An iterator is something which can go over a sequence. That is where the **for** loop comes in. We will see some more examples of the **range ( )** function in the next section.

### for loop

The syntax for **for** loop is just as simple as the while loop. It is specifically designed for going over sequences – like a range for example.

for number in numbers : print ( number )

1 2 3 4 5 6 7 8 9 10

This is consuming a lot of vertical space, right ? By default the print statement always ends with a new line statement ( escape character ‘\n’ ). If you do not want that, you can specify a specific character that the print statement should end with. For example, if we want the print statement to end with a space, do this.

for number in numbers : print ( number , end=" ")

1 2 3 4 5 6 7 8 9 10

Ranges are not the only examples of sequences in Python. There are many more examples like Python Lists, Python Strings, Python Tuples, Python Dictionary, Python sets etc. We will see examples of these in the upcoming sections.

**Challenge** – Print all the odd numbers between 1 and 20

for i in range(0,21) : if i % 2 != 0 : print ( i)

### for vs while loop

Both for and while statements loop through code. While a for loop is used as an iterator, while loop runs indefinitely until a condition is met. Each of these statements have a specific purpose although you can use either of these statements for most situations. Let’s do a couple of challenges to see if you understand the syntaxes well enough.

**Challenge** – Print all the numbers from 1 to 10 using both for loop and while loop

numbers = range(1,11) for number in numbers : print (number, end=" ")

number = 1 while number < 11 : print ( number , end=" ") number = number + 1

**Challenge** – Print numbers 1 to 10 in reverse order using for and while loop

numbers = range(1,11) for number in numbers : print (11-number , end=" ")

**Challenge** – Print the first 10 numbers in the **Fibonacci** series.

What is the Fibonacci series ? It is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.

solution using for loopprev_number = 0 next_number = 1 count = 10 for i in range(count) : print(prev_number, end=" ") next = prev_number + next_number prev_number = next_number next_number = next

prev_number = 0 next_number = 1 count = 0 while count < 10 : print(prev_number, end=" ") next = prev_number + next_number prev_number = next_number next_number = next count = count + 1

**Challenge** – Print all the numbers between 1 and 100 that are multiples of 5’s. For example, 5, 10, 15 and so on.

for number in range(101) : if number % 5 == 0 : print ( number , end=" ")

With this knowledge, let’s move on to the **break** and **continue** statements.

### continue statement

Although **for** and **while** loops are designed to work in a sequence of continuous steps, there are situations where you might want to skip the rest of the processing in the loop when a certain condition is met and move on to the next iteration. Here is a visual on how the continue statement works.

Let’s see this with an example. Say you want to only print the numbers **not** divisible by 5,

for number in range(30) : if number % 5 == 0 : continue print ( number , end= " ")

1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19 21 22 23 24 26 27 28 29

**Challenge** – Find the sum of all the odd numbers between 1 and 100

sum = 0 # holds the initial sum value for number in range(101) : if number % 2 == 0 : # it is even continue sum = sum + number # after the for loop, print the sum print ( sum )

**Challenge** – Find the sum of all the alternate odd numbers between 1 and 100. For example, the odd numbers start with 1,3,5,7,9,11,13 etc. So, in this challenge, you would have to only sum up alternative odd numbers – 1,3,5,7,9,11,13.

sum = 0 alternate = True for number in range(101) : if number % 2 == 0 : continue if alternate == True : sum = sum + number alternate = False continue alternate = True print ( sum )

### break statement

**break** statement literally *breaks* the loop. A *continue* statement just breaks the current iteration while the ** break** statement breaks the loop in its entirity.

Say if you want to find out the sequence of occurance of particular odd number. Here is an example –

In a range, say 1 to 20 , there are 10 odd numbers – 1,3,5,7,9,11,13,15,17,19. Find out the occurance of the 7th odd number.

There is definitely a better mathematical way to do this, but we want to understand how to traverse these numbers and break the loop when we find out what we want.

first = int ( input ( " Enter the first number in the range") ) last = int ( input ( " Enter the last number in the range") ) nth_odd = int ( input ( "Enter the nth occurance of odd number you want to find out")) count = 0 nth_odd_number = 0 for i in range(first,last+1) : if i % 2 != 0 : count = count + 1 if count == nth_odd : nth_odd_number = i break print ( count,"th", " odd number is ", nth_odd_number )

21 th odd number is 41

### Nested loops

Loops can be nested within each other. For example, here is how you print each number ( from 1 to 10 ) as many number of times.

for i in range(1,11) : for count in range(0,i) : print ( i, end=" ") print ()

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10

You can do the same with **while** loops as well. You can nest **for** loop inside a **while** loop and vice-versa. Here is a re-write of the same program as above nesting a **while** loop inside a **for** loop.

for i in range(1,11) : count = i while count > 0 : print ( i, end=" ") count = count - 1 print ()

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10

**Challenge** – Find out all the prime numbers between a given range of numbers. A prime number is a one that is divisible by itself or by 1 and by no other number. An example is 5 – It is divisible only by itself ( other than 1 )

first = int ( input ( "Enter the first number in the range") ) last = int ( input ( "Enter the last number in the range") ) for number in range(first, last+1) : found_prime = True for i in range(2,int((number)/2)+1) : if number % i == 0 : print ( "number ", number , " is not prime") found_prime = False break if found_prime == True : print ( "number ",number, " is prime" ) found_prime = True

**Challenge** – Print multiplication tables from 1 to 10. See example below.

1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 .. 1 x 8 = 8 1 x 9 = 9 1 x 10 = 10 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 .. 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20 ..code

for i in range(1,11) : for j in range(1,11) : print ( i, " x ", j, " = " , i*j)

### for else

This is a syntax that is kind of unique to Python. The syntax applies equally well with **while** statement as well. It is more of a convenience function, but newbies get confused with this syntax some times. It basically means that if nothing is found in the loop, do something in the else part. Typically, when searching for something in a loop, we want to do something when nothing has been found – How would we know if the loop ended because of a **break** statement or if the loop has completed all of its iterations ?

The

elseinfor elseis used to indicate a situation where the loop has been exhausted, not broken.

For example, let’s rewrite the prime number program in the challenge above using **for else** syntax. Say, we want to find out all the prime numbers between 1 and 100.

for i in range(2,101) : for j in range(2,int(i/2)+1) : if i % j == 0 : print ( i, " is not prime number") break else : print ( i, " is a prime number")

2 is a prime number 3 is a prime number 4 is not prime number 5 is a prime number .. 98 is not prime number 99 is not prime number 100 is not prime number

Without the **for else** syntax, we would have to use some kind of flag variables to indicate how the for loop has ended.

for i in range(2, 101) : # flag variable found_prime = True for j in range(2,int((i)/2)+1) : if i % j == 0 : print ( "number ", i , " is not prime") found_prime = False break if found_prime == True : print ( "number ",i, " is prime" ) found_prime = True

number 2 is prime number 3 is prime number 4 is not prime number 5 is prime .. number 98 is not prime number 99 is not prime number 100 is not prime