Loop in Python
Loop and functions are
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
Continue statement is used to bypass a particular instance
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
1
22
333
4444
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 🙂
XtraMous