Programs

Python For Loop Statement Statements: For, While, Nested Loops [Examples]

Gaining expertise in python requires an understanding of every concept of the programming language. In the following article, we will be discussing one such concept of python, i.e. for loop. As it will be extensively used throughout python, understanding the concept is crucial to carry forward with other complex parts of python.  

1. For Loop in Python

In a certain program a block of statements is to be executed repeatedly for several times. Therefore loops are constructed which aids in the repeated execution of the statements. Python for loop is a type of loop statement in python that leads to the multiple executions of a sequence of statements. The iterative process is carried over a sequence like a list, tuple, or string. The indexing variable is not required to be set beforehand in for loop in python.

Syntax of a for loop in python

for x in sequence:

for statements

Where x is any value inside the sequence. The for loop keeps on executing until the last element of the sequence is reached.

An example of for loop in python

 

1. Input: for loop in a list

 

months = [“january”, “february”, “march”]

for x in months:

  if x == “february”:

    continue

  print(x, len(x))

Output: january 7

february 8

march 5

 

2. Input: for loop in a string

 

for x in “computer”:

  print(x)

Output:

c

o

m

p

u

t

e

r

3. Input: sometimes a condition of a break statement can be added before the exhaustion of the sequence.

months = [“january”, “february”, “months”]

for x in months:

if x == “february”:

break

print(x)

Output: january

4. Input: a condition of “continue” statement can be added to stop the iteration process and continue with the next.

months = [“january”, “february”, “march”]

for x in months:

  if x == “february”:

    continue

  print(x)

The range() function

For the iteration of a sequence of numbers, the range() function is used. It is a built-in function that returns a sequence of numbers. The numbers by default start from 0 and increments by 1.  A range(5) function will generate 5 values.

The values of a range() function are not stored in memory and hence, it is important to mention the start number, stop number, and also the increment. Based on these conditions, the function returns the next number.

  • For example : the below program will generate 4 values i.e. 0, 1, 2, and 3.

for x in range(4):

print(x)  

  • The start, stop and step size can also be defined sometimes along with the range() function. If no step size is provided then the default value of 1 is considered. Step is the increment that can be specified in the function.

Syntax: range(start, stop,step_size)

Example: 

Input: range(6, 12)

Output: 6, 7, 8, 9,10,11

Input: range(0, 9, 2)

Output: 0, 2, 4, 6, 8

Input: range(-10, -90, -20)

Output:  -10, -30, -50, -70,

  • The output of the range() function is usually displayed as a list but the function doesn’t actually make a list of the returned items. Therefore this saves memory.  However, if the user wants to return the output in the form of a list, the function list() is used.

Example: 

Input:   print(list(range(6)))

print(list(range(3, 9)))

print(list(range(2, 11, 2)))

Output: [0, 1, 2, 3, 4, 5]

[3, 4, 5, 6, 7, 8]

[2, 4, 6, 8, 10]

The range() function in for loop in python

For iterating through a sequence of numbers, the python for loop range() function can be used on the for loops.

An example is shown below:

Input: months = [‘january’, ‘february’, ‘march’]

for i in range(len(months)):

    print(“I like”, months[i])

Output: I like january

I like february

I like march

2. Python For Loop With Else

The python for loop statements might be sometimes associated with additional statements of “else”. The else statements are executed when the loop is exhausted. 

  • Input: for x in range(4):

print(x)

else:

print(“printing done!”)

Output: 0

1

2

3

printing done!

  • The break condition might be added to ignore the part of “else”. Breaking of a loop statement stops the execution of an else block.

Input: for x in range(5):

if x == 4: break

print(x)

else:

print(“printing done!”)

Output: 0

1

2

3. Python Nested Loops

Nested loops refer to the looping of statements inside a loop.

An example showing a nested loop is: 

season = [“winter”, “summer”, “autumn”]

months = [“january”, “february”, “march”]

for x in season:

 for y in months:

    print(x, y)

Output: 

winter january

winter february

winter march

summer january

summer february

summer march

autumn january

autumn february

autumn march

Conclusion

Loops are an important segment of the python programming language as it enables the user to execute a code in a repeated manner. There might be situations when the user has to use over the same piece of code. In such cases, writing a program becomes easy and takes less time. The article portrayed the use of for loop in python script including various conditions. If you want to learn more about various python projects and topics, checkout this article.

If you are interested in gaining hands-on experience and getting trained by experts in the Python language, you can check out upGrad’s Data Science Program. The course is directed for any age group within 21-45 years of age with minimum eligibility criteria of 50% or equivalent passing marks in graduation. Any working professionals can join this Executive PG program certified from IIIT Bangalore.

With a complimentary python programming bootcamp, the course by upGrad provides 60+ industry projects along with 140+programming tools & languages. Any queries regarding the course are welcomed. 

Where can we use else block with a for loop in Python?

- If the loop is terminated by a break statement, the else clause will not be executed.
- If a loop does not encounter a break statement, the else clause will be executed once after all iterations have been finished.
Following are some of the use-cases of else block with a for loop –
- Instead of using flags, we can use break with else to search.
- It can be used to check for limits or boundaries.
- If you want to execute something based on the fact whether the inner loop was executed successfully or has hit a break statement, you can use the else block.
- If you want to break the flow on exceptions, you can use them.

How to use for loops using range() in Python?<br />

Range is one of Python's built-in immutable sequence types. Range() is used in loops to control how many times the loop is repeated. When using range(), you can give it between one and three integer arguments:
start is the integer value at which the series begins; if this is omitted, the sequence starts at 0.
stop is always required and specifies the number that is tallied up to but not included in the sequence.
If step is omitted, the next iteration's increase (or reduction in the case of negative numbers) is set to 1.
We'll look at an example of different arguments that can be passed to range().
for i in range(0,15,3):
print(i)
Here, the loop starts from 0 and ends at 14 at a step of 3. So, the output is – 0, 3, 6, 9, 12.

Should I choose a while or a for loop in my Python program?

- Before the loop's assertions, a condition must be given in most while condition loops. The statements in the loop's body may never be performed as a result of this. Furthermore, for while loops, it is not always clear how many times the loop will execute. Instead, for loops, concentrate on the iterator, which determines how often the instructions in the loop's body are executed.
- If you know exactly how many elements you want to traverse over, a for loop is preferable. A while loop, on the other hand, is better for evaluating a boolean statement rather than a list of elements to loop over.

Prepare for a Career of the Future

0 replies on “Python For Loop Statement Statements: For, While, Nested Loops [Examples]”

Accelerate Your Career with upGrad

Our Popular Data Science Course

×