How toTech

How to use Loops in Python?

Use loops in Python: Almost every programming language uses the loops. These loops indulge in providing that cushion where you can process a set of lines in repetition. Consider some set of statements in your program. Now these lines have to be executed for ‘n’ number of times. You don’t have to write the same lines for those ‘n’ number of times. You can just simply use these loops which repeat the process unless and until there is an end result. In python language, the same loops are used as in the other programming languages. In this article, we will get to know how to use those loops in Python.

Python has remarkably increased its user experience since its launch in 1991. The users of Python have become so intensive in using it that they now find the other programming languages difficult to execute and operate. On comparison with the other language libraries Python’s library has been so extensive in accustoming its users. Also, the extensive support to libraries and clean object oriented designs increased the productivity of the programmer.

Loops in Python

A looping statement helps us to compile or execute a set of code multiple number of times. In general, the statements are executed sequentially one after the other. When the set of code is in between these statements you can just simply use the loop function to execute those statements for n number of times. In Python, there are major looping statements used. They are
a) For loop
b) While loop
c) Nested loops

Other than these, Python uses some loop control statements. Here are some of the loop control statements in Python.
a) break statement
b) continue statement
c) pass statement

You can also learn on how you can read a file in Python. To read a file in Python, you can visit the below highlighted link

How to read a File in Python

Let us go through some basic descriptions of each loop available in python before we jump into some relevant examples.

For Loop

This loop executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. To simply state it, it says that “for all these statements execute it n number of times”. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.  Here is a basic example of how you can use the for loop in your program.

The syntax of the for loop is as follows,

for iterator_var in sequence:  
statements(s)

This syntax can be used to iterate over iterators and a range. Here is an example to explain the for loop.

#Python program using For loop
#Iterating over a list

print("List Iteration")
l = ["Articles", "for", "Morphigo"]
for i in l:
print(i)



#Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("Morph", "in", "go")
for i in t:
print(i)



#Iterating over a String
print("\nString Iteration")
s = "Morphigo"
for i in s :
print(i)


#Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 565
d['abc'] = 989
for i in d :
print("%s %d" %(i, d[i]))

Now the Output is depicted as follows,

List Iteration
Articles
for
Morphigo

Tuple Iteration
Morph
in
Go

String Iteration
M
o
r
p
h
i
g
o

Dictionary Iteration
xyz 565
abc 989

While Loop

This loop repeats a statement or group of statements while the given statements are true. It tests the condition before it executing the body loop. In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.

The syntax of the While loop is as follows,

while expression:   
statement(s)

All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. Here is an example stating the While loop in Python.

#Python program to illustrate
#while loop
count = 0
while (count < 3):
count = count + 1
print("Hello People")

The output of the above while loop is depicted as follows,

Hello People
Hello People
Hello People

Using the else statement in While loops: In the While loop the loop is executed only for a set of statements which are true. If not, the while loop gets terminated and the statement after the loop gets executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
Here is the while loop with an else statement.

while condition: 
# execute these statements
else:
# execute these statements

Here is a small example with the else statement in the While loop.

#Python program to illustrate
#combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello People")
else:
print("In Else Block")

Now the Output is depicted as follows.

Hello People
Hello People
Hello People
In Else Block

Nested Loops

You can use loop in a loop in Python language. These are termed as the Nested loops. To get into more info in regard to the Nested loops you can refer the examples below. The syntax of the Nested loop is as follows.

for iterator_var in sequence: 
for iterator_var in sequence:
statements(s)
statements(s)

The syntax for the while nested loop is as follows,

while expression:   
while expression:
statement(s)
statement(s)

On a final note we can conclude that the Nested loop can be defined as a loop inside another. This states that a for loop can be included inside a while loop and vice versa. Below is a small basic example to clear more doubts in regard to the nested loops.

#Python program to illustrate
#nested for loops in Python


from_future_ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()

The output for the above illustrated program is as follows.

1
2 2
3 3 3
4 4 4 4

You can also delve into how you can print your programs in Python with relevant examples. Explore the link below to learn how you can print in Python with relevant examples.

How to print in Python with relevant examples

Loop Control Statements

Loop control statements are used to change the execution from the normal sequence. If ever an execution creates a scope, all the automatic statements in that scope are destroyed. As already mentioned above, Python supports three major loop control statements. They are Break, Continue and Pass.

We will go through each of the loop control statements below.

Continue statement: It returns the control to the beginning of the loop.

#Prints all letters except 'e' and 's' 
for letter in 'morphigo in a go':
if letter == 'g' or letter == 'o':
continue
print 'Current Letter :', letter
var = 10

Output is now depicted as follows,

Current letter : m
Current letter : r
Current letter : p
Current letter : h
Current letter : i
Current letter : g
Current letter : i
Current letter : n
Current letter : a

Break statement: It brings control out of the loop

for letter in 'morphigo':
# break the loop as soon it sees 'e'
# or 's'
if letter == 'p' or letter == 'o':
break

print 'Current Letter :', letter

The output of the above program is as shown,

Current letter : p

Pass statement: We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.

#An empty loop
for letter in 'Morphigo':
pass
print 'Last Letter :', letter


The output of the above statement is depicted as shown below

Last letter : o

FAQ’s

Now, we will look into some top 3 FAQ’s on web. We have handpicked them for you so that we can clear up any relevant doubts in your mind.

Does Python do Until loop?

The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code.

What is While true in Python?

While True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) “true”. True always evaluates to boolean “true” and thus executes the loop body indefinitely. It’s an idiom that you’ll just get used to eventually!

What is Time sleep in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds.

To conclude: Hence, we have learnt the different looping statements and their use in Python through this article. Comment your views below in the comment section and do share the content. For more of some interesting stuff in regard to the tech articles and news visit Morphigo.com. Cheers !

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close