Loops in Python 3 - A Definitive Guide For Beginners

In the previous post, we got started with the python lesson which gave some basic idea about the syntax on Conditional Statements mostly If..else. We got started by declaring variables and then we proceeded to check various datatypes with Conditional Statements. In this lesson, we are going to continue with understanding conditional statements with loops(for loop and while loop) in python. This lesson is again a beginner course to help you understand the basic concept. This post will cover different types of Loops in python and its usage in details.



Prerequisite for this course

  1.  A beginner 
  2.  python installed System (IDE/Interpreter). 
  3.  Knowledge of Variables.
  4.  Knowledge of Conditional Statements(If..Else).
  5. A notepad to take notes.

Why do we use Loop?


In order to know why we use looping in programming, we will first, be aware that different programming languages have different for loops. In Python, for instance, you can iterate through all the items in a list by writing loops.

Loops are used in programming as a test to know if the arguments in a clause are true or false and then determine to do an action that may involve skipping the clause and going to the next one. There are many different types of looping. If your loop only needs a test to decide if it should keep looping or not, then a do-while fits that. If you code a do-while loop and then graft on extra statements to initialize the loop counter and to increment the loop counter, then your program would likely be clearer if you'd just written a C-style loop in the first place.




The For Loop:

In Python, you can use the “for” loop in the following manner.

for <iter> in <sequence>:
    <statements(iter)>

The “iter” represents the iterating variable. It gets assigned with the successive values from the input sequence.


The “sequence” may refer to any of the following Python objects such as a list, a tuple or a string.
Let's take a look into a simple example to understand the syntax.

a =[10,20,30,40,50,60,70,80,90,100] ### Creating List to iterate
for i in a: ### Interating the list a
    print(i) ## Printing the elements in the list a
--------------
10
20
30
40
50
60
70
80
90
100
Here’s what’s happening in this example:

  1. a is initially a list with 10 elements from 1...100. Now we need to iterate/traverse the list using for loop.
  2. We use For Statement with expr variable i which points to each value present in a.
  3. The loop keep executing until all the elements is traversed and keeps printing all the value present on the list.
  4. This continues until i becomes i>length of list. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.
Do we have better way if we dont want to loop the whole list?

Yes, the range () function.

it generates a list of numbers, which is generally used to iterate over with for loops. There's many use cases. Often you will want to use this when you want to perform an action X number of times, where you may or may not care about the index. Other times you may want to iterate over a list (or another iterable object), while being able to have the index available.


Range() Syntax:
range(stop) ## Takes on arguments
range(start, stop) ## Takes two arguments
range(start, stop, step) ## Takes three arguments

range(stop)
When you call range() with one argument, you will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number you have provided as the stop.

Example:

for i in range(2): ###Range(stop)
    print(i)
----------------
0

1

How does this example works:

  1. We are passing the stop variable to the range function.
  2. The loop will start from 0 and iterate till the stop variable i.e(2)
  3. The loop exits once it matches the stop arguments passed.


range(start, stop)

When you call range() with two arguments, you get to decide not only where the series of numbers stops but also where it starts, so you don’t have to start at 0 all the time. You can use range() to generate a series of numbers from A to B using a range(A, B). Let’s find out how to generate a range starting at 1.

Example:

### range is equal to 1 to n(exclusive)
for i in range(1,5):
print(i)
------------------
1
2
3
4

How does this example works:

  1. The loop start from 1 instead of the default 0 , Since we provided with the start arguments.
  2. The loop iterates till it reaches the stop arguments 5(exclusive) from the start arguments.
  3. The loop terminates on it matches the stop arguments.


range(start,stop,step)

When you call range() with three arguments, you can choose not only where the series of numbers will start and stop but also how big the difference will be between one number and the next. If you don’t provide a step, then range() will automatically behave as if the step is 1.

Example:

for i in range(3, 16, 4):
print(i)
-------------------
3
7
11
15

How does this example works:

  1. The loop start from 3 instead of the default 0 , Since we provided with the start arguments.
  2. The loop iterates till it reaches the stop arguments 16 from the start arguments.
  3. The loop terminates on it matches the stop argument.
  4. Here we have passed the step arguments which takes the step added while iterating as in this cases by 4

Can the steps in range() in python be negative or Zero ?

Yes , I Will give this as exercise for practice ,but we can have negative as steps which will be used in decrement while iterating.
But for 0 its not possible It will not allow to run the loops.You will face with "ValueError: range() arg 3 must not be zero".

You can try both the example as practice.

Practice Example to understand the earlier discussed topics.

Example 1: Checking if the range of number is divisible by 3.

## Checking if num is divisible by 3

## range 100 includes 0..100
## It will check for all number in the range and if its reminder == 0 prints the number
for i in range(20):
    if i%3==0:
        print(i)
------------------------
0
3
6
9
12
15
18

Example 2 : A little bit tricky example of printing patterns.

## Printing list in pattern
# 10 is the total number to print
for num in range(10):
for i in range(num):
print (num, end=" ") #print number
# new line after each row to display pattern correctly
print("\n")
--------------------------------------
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

The next topic which we are going to see is in loops , The While loop.

While Loop


Syntax

while :
<statements>


When a while loop is encountered, is first evaluated in Boolean context. If it is true, the loop body is executed. Then is checked again, and if still true, the body is executed again. This continues until becomes false, at which point program execution proceeds to the first statement beyond the loop body.


Lets take a example to understand the Syntax:

n = 0
while n < 5:
    print(n)
    n += 1
------------
0
1
2
3
4

Here’s what’s happening in this example:

  1. n is initially starts from 0, The loop starts and since n<5 It executes the print statement and increment the n values.
  2. It goes back to Check if the value is greater than 5 after incrementing.
  3. Its goes on until the n is greater than 5 and the expression tested for false and gets terminated.
  4. Note that the controlling expression of the while loop is tested first, before anything else happens. If it’s false to start with, the loop body will never be executed at all.


Bonus Example for better understanding

count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")
--------------------------------
0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5



Break and Continue statements

In each example you have seen so far, the entire body of the while loop is executed on each iteration. Python provides two keywords that terminate a loop iteration prematurely:

break immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body.

continue immediately terminates the current loop iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate.

We will straight jump into example to understand it better but using For loop.

for val in "NintyZeros":
    if val == "Z":
        break
    print(val)

print("The end")
------------------
N
i
n
t
y
The end

Lets see whats happening in the example:


  1.  The For loops takes each character from String "NintyZeros" into val.
  2.  We are using conditional statements (if) to check if it matches with Character 'Z'.
  3.  It keeps on printing until it matches with the character.
  4.  Once the match is found it executes the break statements and exit the loop.



for val in "NintyZeros":
    if val == "Z":
        continue
    print(val)

print("The end")
-----------------------
N
i
n
t
y
e
r
o
s
The end

Lets see whats happening in the example:

  •  The For loops takes each character from String "NintyZeros" into val.
  •  We are using conditional statements (if) to check if it matches with Character 'Z'.
  •  It keeps on printing until it matches with the character.
  •   Once the match is found it skips the continue statements and continue the loop till it reaches end of String.


The else with While:

Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not found in most other programming languages. The syntax is shown below:

Syntax:

while <condtion>:
    <statement>
else:
    <additional_statement>

#Example:
 

A = [10,20,30,40]
B= 50

i=0
while i<len(A):
    if A[i] == B:
        print(B,"Found")
        break
    i+=1
else:
    print(B,"Not found")
----------------------
50 Not found

In the above example:

  1.      The while loop start iterating the list A until it reaches the length of A.
  2.      It verifies if the value of variable B matches with any of the element in list A.
  3.      if it matches breaks the loop and prints "Found"
  4.      Once the loop reaches the length of the list it goes to Else statement to print "Not found".

Practice Example:

Check if the number is prime or not.

# Python program to check if the input number is prime or not


num = 520
#num = 37
# take input from the user
# num = int(input("Enter a number: "))

# prime numbers are greater than 1
if num > 1:
   # check for factors
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           break
   else:
       print(num,"is a prime number")
     
# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")



A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.

In this program, variable num is checked if it's prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.

We check if num is exactly divisible by any number from 2 to num - 1. If we find a factor in that range, the number is not prime. Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.
We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number; otherwise the number is prime.

That''s the end of  topic on loops in python .Hope it make sense of writing such a deep and long post.

Happy Coding!👍

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media


EmoticonEmoticon