Meritshot Tutorials

  1. Home
  2. »
  3. introduction to Loops in Python

Python Tutorial

Introduction to Loops

What is a Regular Expression?

Sometimes a programmer wants to execute a group of statements a certain number of times. This can be done using loops.This can be particularly useful when you need to perform repetitive tasks, such as iterating over a list of items or running a piece of code until a certain condition is met. If you remeber we already used loops before when we were iterating through lists and tuples. loops are further classified into following main types:

* for loop * while loop ## The For Loop:

for loops can iterate over a sequence of iterable objects in python. Iterating over a sequence is nothing but iterating over strings, lists, tuples, sets and dictionaries. ### Example: iterating over a string:

name = ‘Abhishek’

for   i in   name: print(i, end=”, “)

A, b, h, i, s, h, e, k,

Example: iterating over a list

colors = [“Red”, “Green”, “Blue”, “Yellow”]

for x in colors: print(x)

Red

Green

Blue

Yellow

Similarly, we can use loops for lists, sets and dictionaries.

1.0.2 Interesting Example :

Imagine you have a list of sheep:

 sheep = [“Shaun”, “Timmy”, “Lazylegs”, “Shirley”]

You want to count how many sheep you have. You can use a for loop to go through each sheep and count them:

count = 0

for sheep_name in sheep: count = count + 1

print(“I have”, count, “sheep.”)

have 4 sheep.

  • count starts at
  • The for loop goes through each sheep in the sheep
  • For each sheep, we add 1 to the
  • Finally, we print the total count

1.1 range():

What if we do not want to iterate over a sequence? What if we want to use for loop for a specific number of times?

For example we want to use the for loop for counting numbers

Here, we can use the range() function.

for k in range(5):

print(k)

0

1

2

3

4

Here, we can see that the loop starts from 0 by default and increments at each iteration. But we can also loop over a specific range.

for k in range(4,9):

print(k)

4

5

6

7

8

There is also a third parameter in range known as step:

* start (optional): The starting number of the sequence. Defaults to 0 if not specified. * stop: The endpoint of the sequence, which is not included in the sequence. * step (optional): The difference between each number in the sequence. Defaults to 1

for i in range(1, 10, 2):

print(i)

1

3

5

7

9

1.2 Python while Loop

As the name suggests, while loops execute statements while the condition is True. As soon as the condition becomes False, the interpreter comes out of the while loop.

count = 5

while (count > 0):

print(count) count = count – 1

5

4

3

2

1

Here, the count variable is set to 5 which decrements after each iteration. Depending upon the while loop condition, we need to either increment or decrement the counter variable (the variable count, in our case) or the loop will continue forever.

1.3 Else with While Loop

We can even use the else statement with the while loop. Essentially what the else statement does is that as soon as the while loop condition becomes False, the interpreter comes out of the while loop and the else statement is executed.

x = 5

while (x > 0):

print(x)

x = x – 1

else:

print(‘counter is 0’)

5

4

3

2

1

counter is 0

Example:

Imagine a gatekeeper at a party. The gatekeeper checks if you’re on the guest list. If you are, you can enter. If not, you have to wait outside.

A while loop is like that gatekeeper. It checks a condition. If the condition is true, it lets you do something. If not, it keeps you waiting.

age = 15

while  age < 18:

print(“You’re too young to enter! Try next year”) age = age + 1

print(“You’re old enough to enter!”)

You’re too young to enter! Try next year You’re too young to enter! Try next year You’re too young to enter! Try next year You’re old enough to enter!

Explanation:

  • age is the person trying to enter the
  • The while loop is the
  • The condition is age < As long as the person is younger than 18, they can’t enter.
  • Inside the loop, we print a message and increase the age by 1 (like waiting for the next year).
  • Once the person is 18 or older, the condition becomes false, and the loop So, a while loop keeps doing something as long as a condition is true.

1.4 Do-While loop in python

do..while is a loop in which a set of instructions will execute at least once (irrespective of the condition) and then the repetition of loop’s body will depend on the condition passed at the end of the while loop. It is also known as an exit-controlled loop ## How to emulate do while loop in python?

To create a do while loop in Python, you need to modify the while loop a bit in order to get similar behavior to a do while loop.

The most common technique to emulate a do-while loop in Python is to use an infinite while loop with a break statement wrapped in an if statement that checks a given condition and breaks the iteration if that condition becomes true:

while True:

number = int(input(“Enter a positive number: “)) print(number)

if not number > 0:

break

Enter a positive number: 6 6

Enter a positive number: 7 7

Enter a positive number: 9 9

Enter a positive number: 1 1

Enter a positive number: -5

-5

This loop uses True as its formal condition. This trick turns the loop into an infinite loop. Before the conditional statement, the loop runs all the required processing and updates the breaking condition. If this condition evaluates to true, then the break statement breaks out of the loop, and the program execution continues its normal path.