Register Now


Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Register Now

It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways

Loop in Python

Loop and functions are two most important topics in the basics of Python. You need to have a really good hand on loop and functions.

Loop is basically used to iterate the same thing again and again. Python, like most of the programming language, have two types of loop:-
1. while
2. for

While loop
In a while loop, a condition is checked first and then the content or body of the loop is executed.
A simple while loop is executed below

There are two more keywords which are used inside the body of a loop:-
1. break
2. continue

Break command is used to stop a loop at a particular condition and it pulls the control out of the loop. See the example below

Break statement stops the loop at the given condition

Continue statement is used to bypass a particular instance

Use of continue statement

2. For loop

A for loop is used for iterating over a sequence which could be anything like a list, a tuple, a dictionary or a set.

Let’s understand each with the help of some examples:

a. Applying loop on a list

b. Applying loop on a list with break statement

c. Using range keyword. Range starts with 0 and ends at n-1 where n is the parameter in the range() function

d. Using range keyword with increment

e. Nested loop

f. Looping through all the key-value pair of a dictionary

g. Looping through all the values of a dictionary

h. Looping through all the keys of a dictionary

i. Print the following pattern

j. Reverse a list using loop

h. Reverse a string using loop, example to do it without loop is given below:

If you want to learn more about some tricky Python Questions then do check out our book on Amazon

1. 100 Python Questions to crack Data Science/Analyst Interview
2. The Monk who knew Linear Regression (Python): Understand, Learn and Crack Data Science Interview

Keep practicing Machaa 🙂


About TheDataMonkContributor

I am the Co-Founder of The Data Monk. I have a total of 4+ years of analytics experience with 3+ years at Mu Sigma and 1 year at OYO. I am an active trader and a logically sarcastic idiot :)

Follow Me

Leave a reply