0% found this document useful (0 votes)
12 views43 pages

Python Loop Types: For, While, Nested

The document provides an overview of loops in Python, detailing the two primary types: for loops and while loops. It explains their usage, including loop control statements like break, continue, and pass, as well as the concept of nested loops. Additionally, it touches on the simulation of do-while loops and the use of else statements with loops.

Uploaded by

Testimony Peter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views43 pages

Python Loop Types: For, While, Nested

The document provides an overview of loops in Python, detailing the two primary types: for loops and while loops. It explains their usage, including loop control statements like break, continue, and pass, as well as the concept of nested loops. Additionally, it touches on the simulation of do-while loops and the use of else statements with loops.

Uploaded by

Testimony Peter
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

In Python, loops are used to repeat a block of code multiple times.

The two primary types of loops are


for loops and while loops. Python also supports loop control statements and nested loops.

Types of Loops

for loops are used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block
of code for each item in the sequence. This is ideal when you know the number of iterations in advance
or are processing elements of a collection.

python

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

You can also use the range() function to loop a specific number of times:

python

for i in range(4): # range(4) generates numbers 0, 1, 2, 3

print("Iteration number:", i)

while loops are used to execute a block of statements repeatedly as long as a given condition remains
true. This is suitable for situations where the number of iterations is not known beforehand, and the
loop continues until a certain condition is met.

python

count = 0

while count < 3:

print("Count is:", count)

count = count + 1 # Increment the counter to avoid an infinite loop

Nested Loops involve placing one loop inside another. The inner loop executes completely for each
iteration of the outer loop.

Loop Control Statements

These statements change the normal flow of loop execution:

break: Terminates the loop entirely when a specified condition is met, redirecting program flow to the
statement immediately after the loop.
continue: Skips the current iteration of the loop and moves to the next iteration.

pass: Acts as a placeholder within a loop where a statement is required by syntax but no action is
needed. It does nothing.

For more detailed tutorials and interactive examples, you can refer to resources like W3Schools Python
Loops or the [GeeksforGeeks guide on Python loops]([Link] [Link]/python/loops-in-
python/).

Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through
items) and While loops (based on conditions).

For Loop

For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a
block of code repeatedly, once for each item in the sequence.

n=4

for i in range(0, n):

print(i)

Output

Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a
range from 0 to n-1 (where n = 4).

Example:

Iterating Over List, Tuple, String and Dictionary Using for Loops in Python
li = ["geeks", "for", "geeks"]

for x in li:

print(x)

tup = ("geeks", "for", "geeks")

for x in tup:

print(x)

s = "abc"

for x in s:

print(x)

d = dict({'x':123, 'y':354})

for x in d:

print("%s %d" % (x, d[x]))

set1 = {10, 30, 20}

for x in set1:

print(x),

Output

geeks
for

geeks

geeks

for

geeks

x 123

y 354

10

20

30

Iterating by Index of Sequences

We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the
length of the list and then iterate over the sequence within the range of this length.

li = ["geeks", "for", "geeks"]

for index in range(len(li)):

print(li[index])

Output

geeks
for

geeks

Explanation: This code iterates through each element of the list using its index and prints each element
one by one. The range(len(list)) generates indices from 0 to the length of the list minus 1.

orial

Data Types

Interview Questions

Examples

Quizzes

DSA Python

Data Science

NumPy

Pandas

Practice

Open In App

Loops in Python - For, While and Nested Loops

Last Updated : 04 Oct, 2025

Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through
items) and While loops (based on conditions).

For Loop

For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a
block of code repeatedly, once for each item in the sequence.
n=4

for i in range(0, n):

print(i)

Output

Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a
range from 0 to n-1 (where n = 4).

For Loops in Python

Example:

Iterating Over List, Tuple, String and Dictionary Using for Loops in Python

li = ["geeks", "for", "geeks"]

for x in li:

print(x)

tup = ("geeks", "for", "geeks")


for x in tup:

print(x)

s = "abc"

for x in s:

print(x)

d = dict({'x':123, 'y':354})

for x in d:

print("%s %d" % (x, d[x]))

set1 = {10, 30, 20}

for x in set1:

print(x),

Output

geeks

for

geeks

geeks

for

geeks

c
x 123

y 354

10

20

30

Iterating by Index of Sequences

We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the
length of the list and then iterate over the sequence within the range of this length.

li = ["geeks", "for", "geeks"]

for index in range(len(li)):

print(li[index])

Output

geeks

for

geeks

Explanation: This code iterates through each element of the list using its index and prints each element
one by one. The range(len(list)) generates indices from 0 to the length of the list minus 1.

While Loop

In Python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the program is
executed.
In below code, loop runs as long as the condition cnt < 3 is true. It increments the counter by 1 on each
iteration and prints "Hello Geek" three times.

cnt = 0

while (cnt < 3):

cnt = cnt + 1

print("Hello Geek")

Output

Hello Geek

Hello Geek

Hello Geek

Infinite While Loop

If we want a block of code to execute infinite number of times then we can use the while loop in Python
to do so.

Code given below uses a 'while' loop with the condition "True", which means that the loop will run
infinitely until we break out of it using "break" keyword or some other logic.

while (True):

print("Hello Geek")

Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition
is always true and we have to forcefully terminate the compiler.

Nested Loops

Python programming language allows to use one loop inside another loop which is called nested loop.
Following example illustrates the concept.

from __future__ import print_function

for i in range(1, 5):

for j in range(i):
print(i, end=' ')

print()

Output

22

333

4444

Explanation: In the above code we use nested loops to print the value of i multiple times in each row,
where the number of times it prints i increases with each iteration of the outer loop. The print() function
prints the value of i and moves to the next line after each row.

A final note on loop nesting is that we can put any type of loop inside of any other type of loops in
Python. For example, a for loop can be inside a while loop or vice versa.

Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed. Python supports the following
control statements.

Continue Statement

The continue statement in Python returns the control to the beginning of the loop.

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

continue

print('Current Letter :', letter)

Output
Current Letter : g

Current Letter : k

Current Letter : f

Current Letter : o

Current Letter : r

Current Letter : g

Current Letter : k

Explanation: The continue statement is used to skip the current iteration of a loop and move to the next
iteration. It is useful when we want to bypass certain conditions without terminating the loop.

Break Statement

The break statement in Python brings control out of the loop.

for letter in 'geeksforgeeks':

if letter == 'e' or letter == 's':

break

print('Current Letter :', letter)

Output

Current Letter : e

Explanation: break statement is used to exit the loop prematurely when a specified condition is met. In
this example, the loop breaks when the letter is either 'e' or 's', stopping further iteration.

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for empty control statements,
functions and classes.

for letter in 'geeksforgeeks':

pass
print('Last Letter :', letter)

Output

Last Letter : s

Explanation: In this example, the loop iterates over each letter in 'geeksforgeeks' but doesn't perform
any operation, and after the loop finishes, the last letter ('s') is printed.

Python Do While Loops

Last Updated : 23 Jul, 2025

In Python, there is no construct defined for do while loop. Python loops only include for loop and while
loop but we can modify the while loop to work as do while as in any other languages such as C++ and
Java.

In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is
initially True and then break out of the loop when the desired condition is met.

Do while loop

Do while loop is a type of control looping statement that can run any statement until the condition
statement becomes false specified in the loop. In do while loop the statement runs at least once no
matter whether the condition is false or true.

Syntax of do while loop:

do{

// statement or

// set of statements

while(condition)

Example of do while loop in C++

In this example, we are going to print multiple of 2 using the do while loop. So, that we can understand
the working of do while loop.
#include <iostream>

using namespace std;

int main() {

int i=0;

// Defining do while loop

// to write multiple of 2

do{

i++;

cout<<"2 x "<<i<<"="<<2*i<<endl;

}while(i<5);

return 0;

Output: In the below output we can clearly see that program also prints "2 x 5=10" even though 5 is not
less than 5.

2 x 1=2

2 x 2=4

2 x 3=6

2 x 4=8

2 x 5=10

Examples of do while loop in Python :

Example 1 :
In this example, we are going to implement the do-while loop in Python using the while loop and if
statement in Python and comparing the while loop with the do-while loop in python.

# defining list of strings

list1 = ["geeksforgeeks", "C++",

"Java", "Python", "C", "MachineLearning"]

# initialises a variable

i=0

print("Printing list items\

using while loop")

size = len(list1)

# Implement while loop to print list items

while(i < size):

print(list1[i])

i = i+1

i=0

print("Printing list items\

using do while loop")

# Implement do while loop to print list items

while(True):

print(list1[i])

i = i+1
if(i < size and len(list1[i]) < 10):

continue

else:

break

Output: The while is printing the items in the list. The Do while loop is having two conditions for
terminating.

The pointer of the list reached its last+1 position and any element of the list index having length >=10. In
this code output, we can see that-

The Do While loop is terminated, because the condition len(list1[5])<10 is not fulfilling.

Printing list items using while loop

geeksforgeeks

C++

Java

Python

MachineLearning

Printing list items using do while loop

geeksforgeeks

C++

Java

Python

C
total = 0

# loop will run at least once

while True:

# ask the user to enter a number

num = int(input("Enter a number (or 0 to exit): "))

# exit the loop if the user enters 0

if num == 0:

break

total += num

# print the total

print("Total:", total)

Output: In this code, we can see that a while loop is running and accepting the input from the user and
adding it. When 0 is entered then it will break out of the loop and print the sum of all numbers which
adds input by the user before 0.

Enter a number (or 0 to exit): 1

Enter a number (or 0 to exit): 3

Enter a number (or 0 to exit): 2

Enter a number (or 0 to exit): 0

Total: 6

Python Tutorial

Data Types

Interview Questions
Examples

Quizzes

DSA Python

Data Science

NumPy

Pandas

Practice

Open In App

Using Else with Loops in Python

Last Updated : 04 Oct, 2025

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted
with the if conditional statements. But Python also allows us to use the else condition with for loops.

The else block just after for/while is executed only when the loop is NOT terminated by a break
statement.

Else block is executed in below Python 3.x program:

for i in range(1, 4):

print(i)

else: # Executed because no break in for

print("No Break")

Output :

1
2

No Break

Else block is NOT executed in Python 3.x or below:

for i in range(1, 4):

print(i)

break

else: # Not executed as there is a break

print("No Break")

Output :

Such type of else is useful only if there is an if condition present inside the loop which somehow
depends on the loop variable.

In the following example, the else statement will only be executed if no element of the array is even, i.e.
if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in
the third iteration of the loop and hence the else present after the for loop is ignored. In the case of
array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.

# Python 3.x program to check if an array consists

# of even number

def contains_even_number(l):

for ele in l:

if ele % 2 == 0:

print ("list contains an even number")

break
# This else executes only if break is NEVER

# reached and loop terminated after all iterations.

else:

print ("list does not contain an even number")

# Driver code

print ("For List 1:")

contains_even_number([1, 9, 8])

print (" \nFor List 2:")

contains_even_number([1, 3, 5])

Output:

For List 1:

list contains an even number

For List 2:

list does not contain an even number

As an exercise, predict the output of the following program.

count = 0

while (count < 1):

count = count+1

print(count)

break

else:
print("No Break")

Difference between for loop and while loop in Python

Last Updated : 11 Sep, 2025

At a glance, the difference is simple:

For loop: runs a fixed number of times, usually when you already know how many times you want the
code to repeat.

While loop: runs until a condition becomes false, which is useful when you don’t know in advance how
many times it should run.

For loop in Python

Python For Loops are used for iterating over a sequence like lists, tuples, strings and ranges.

For loop allows you to apply the same operation to every item within loop.

Using For Loop avoid the need of manually managing the index.

For loop can iterate over any iterable object, such as dictionary, list or any custom iterators.

For Loop Example:

s = ["Geeks", "for", "Geeks"]

# using for loop with string

for i in s:

print(i)

Output

Geeks

for

Geeks

Python for Loop Flowchart


For loop in Python

For Loop Flow chart

While Loop in Python

Python While Loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the program is
executed.

While Loop Example:

# Python example for while loop

count = 0

while (count < 3):

count = count + 1

print("Hello Geek")

Output

Hello Geek

Hello Geek

Hello Geek

Python while Loop Flowchart

While Loop in Python

While Loop Flow chart

Comparison Table

Now, we will compare both loops in Python to understand where to use 'for loop' and where to use
'while loop'.

For loop

While loop
For loop is used to iterate over a sequence of items.

While loop is used to repeatedly execute a block of statements while a condition is true.

For loops are designed for iterating over a sequence of items. Eg. list, tuple, etc.

While loop is used when the number of iterations is not known in advance or when we want to repeat a
block of code until a certain condition is met.

For loop require a sequence to iterate over.

While the loop requires an initial condition that is tested at the beginning of the loop.

For loop is typically used for iterating over a fixed sequence of items

While loop is used for more complex control flow situations.

For loop is more efficient than a while loop when iterating over sequences, since the number of
iterations is predetermined and the loop can be optimized accordingly.

While a loop may be more efficient in certain situations where the condition being tested can be
evaluated quickly.

Python Tutorial

Data Types

Interview Questions
Examples

Quizzes

DSA Python

Data Science

NumPy

Pandas

Practice

Open In App

Use for Loop That Loops Over a Sequence in Python

Last Updated : 11 Sep, 2025

Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, set,
String, etc. A sequence consists of multiple items and this item can be iterated using in keyword and
range keyword in for loop.

Example 1: Python For Loop using List

A list is used to store the multiple values of the different types under a single variable. It is mutable i.e.,
items in the list can be changed after creation. The list is created by enclosing the data items with square
brackets.

# list creation

a = ["Geeks", "for", "Geeks"]

for i in a:

print(i)

print('-----')

for i in range(len(a)):

print(a[i])
Output

Geeks

for

Geeks

-----

Geeks

for

Geeks

Example 2: Python For Loop using Tuple

A tuple is used to store the multiple values of the different types under a single variable. It is immutable
i.e., items in a tuple cannot be changed after creation. A tuple is created by enclosing the data items
with round brackets.

# tuple creation

tup = ("Geeks", "for", "Geeks",

"GFG", "Learning", "Portal")

for i in tup:

print(i)

print('-----')

for i in range(3, len(tup)):

print(tup[i])

Output

Geeks

for

Geeks

GFG
Learning

Portal

-----

GFG

Learning

Portal

Example 3: Python For Loop using Dictionary

Dictionary is an unordered collection of items where data is stored in key-value pairs. Unlike other data
types like list, set and tuple it holds data as key: value pair. for loop uses in keyword to iterate over each
value in a dictionary.

# dictionary creation

d = {1: "a", 2: "b", 3: "c", 4: "d"}

for i in d:

print(i)

Output

Example 4: Python For Loop using Set

A set is an unordered, unindexed, and immutable datatype that holds multiple values under a single
variable. It can be created by surrounding the data items around flower braces or a set method. As the
set is unindexed range method is not used.

# set creation

set1 = {"unordered", "unindexed", "immutable"}


for i in set1:

print(i)

Output

unordered

unindexed

immutable

Example 5: Python For Loop using String

Here we passed the step variable as 2 in the range method. So we got alternate characters in a string.

# string creation

str = "GFG Learning-Portal"

for i in str:

print(i, end="")

print()

for i in range(0, len(str), 2):

print(str[i], end="_")

Output

GFG Learning-Portal

G_G_L_a_n_n_-_o_t_l_

Eliminating Loop from Python Code

Last Updated : 11 Sep, 2025

In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.
Eliminate Loops with List Comprehension

A List comprehensions are another way to generate lists without the need for explicit loop structures.

# Without list comprehension

a = []

for i in range(8):

[Link](i**2)

# With list comprehension

b = [i**2 for i in range(8)]

print("Using Loop: ", a)

print("Using List Comprehension: ", b)

Output

Using Loop: [0, 1, 4, 9, 16, 25, 36, 49]

Using List Comprehension: [0, 1, 4, 9, 16, 25, 36, 49]

Explanation:
n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.

In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7

Eliminate Loops with Itertools

The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.

import itertools

# Flattening a list of lists using a loop

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = []

for sublist in a:

for i in sublist:

[Link](i)

print(b)

# Flattening a list of lists using itertools

b = list([Link](*a))

print(b)

Python Tutorial

Data Types

Interview Questions

Examples

Quizzes

DSA Python

Data Science
NumPy

Pandas

Practice

Open In App

Eliminating Loop from Python Code

Last Updated : 11 Sep, 2025

In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.

Eliminate Loops with List Comprehension

A List comprehensions are another way to generate lists without the need for explicit loop structures.

# Without list comprehension

a = []

for i in range(8):

[Link](i**2)

# With list comprehension

b = [i**2 for i in range(8)]


print("Using Loop: ", a)

print("Using List Comprehension: ", b)

Output

Using Loop: [0, 1, 4, 9, 16, 25, 36, 49]

Using List Comprehension: [0, 1, 4, 9, 16, 25, 36, 49]

Explanation:

n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.

In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7

Eliminate Loops with Itertools

The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.

import itertools

# Flattening a list of lists using a loop

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = []

for sublist in a:

for i in sublist:
[Link](i)

print(b)

# Flattening a list of lists using itertools

b = list([Link](*a))

print(b)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Remove Loops with Pandas

You can eliminate loops while working with numerical data, and libraries in Python such as NumPy and
Pandas. These Libraries leverage a technique called Vectorization. It generally performs operations on
the entire array of data.

Let's consider a simple example in which we need to square each number in a list and the range is given
from 1 to 6.

Example: By using a for loop

numbers = list(range(1, 6))

squares = []

for number in numbers:

[Link](number ** 2)

print(squares)

Output

[1, 4, 9, 16, 25]

Example: By using NumPy


import numpy as np

numbers = [Link](1,6)

squares = numbers ** 2

print(squares)

Output

[ 1 4 9 16 25]

Eliminate Loops with Built-in Functions: map(), reduce, and filter()

Python's built-in function "map()", "reduce()", and "filter()" provides powerful, functional programming
alternatives to loops.

"map()": It applies a function to all items in an input list.

numbers = list(range(1, 6))

squares = list(map(lambda x: x ** 2, numbers))

print(squares)

Python Tutorial

Data Types

Interview Questions

Examples

Quizzes

DSA Python

Data Science

NumPy

Pandas

Practice


Open In App

Eliminating Loop from Python Code

Last Updated : 11 Sep, 2025

In Python, loops like for and while are very common for repeating tasks. But sometimes, writing loops
makes the code longer, slower, or harder to read. In many cases, you can eliminate loops by using
Python’s built-in features, which are faster and cleaner.

Eliminate Loops with List Comprehension

A List comprehensions are another way to generate lists without the need for explicit loop structures.

# Without list comprehension

a = []

for i in range(8):

[Link](i**2)

# With list comprehension

b = [i**2 for i in range(8)]

print("Using Loop: ", a)

print("Using List Comprehension: ", b)

Output

Using Loop: [0, 1, 4, 9, 16, 25, 36, 49]


Using List Comprehension: [0, 1, 4, 9, 16, 25, 36, 49]

Explanation:

n the first part, a normal for loop is used. It starts with an empty list a and keeps appending each
squared number (i**2) one by one.

In the second part, a list comprehension does the same thing but in a single line: it directly creates a list
of squares of numbers from 0 to 7

Eliminate Loops with Itertools

The Python itertools modules are a collection of tools for handling iterators. They can eliminate the
need for complex loops and make code more efficient and cleaner.

import itertools

# Flattening a list of lists using a loop

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = []

for sublist in a:

for i in sublist:

[Link](i)

print(b)

# Flattening a list of lists using itertools

b = list([Link](*a))
print(b)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Remove Loops with Pandas

You can eliminate loops while working with numerical data, and libraries in Python such as NumPy and
Pandas. These Libraries leverage a technique called Vectorization. It generally performs operations on
the entire array of data.

Let's consider a simple example in which we need to square each number in a list and the range is given
from 1 to 6.

Example: By using a for loop

numbers = list(range(1, 6))

squares = []

for number in numbers:

[Link](number ** 2)

print(squares)

Output

[1, 4, 9, 16, 25]

Example: By using NumPy


import numpy as np

numbers = [Link](1,6)

squares = numbers ** 2

print(squares)

Output

[ 1 4 9 16 25]

Eliminate Loops with Built-in Functions: map(), reduce, and filter()

Python's built-in function "map()", "reduce()", and "filter()" provides powerful, functional programming
alternatives to loops.

"map()": It applies a function to all items in an input list.

numbers = list(range(1, 6))

squares = list(map(lambda x: x ** 2, numbers))

print(squares)

Output
[1, 4, 9, 16, 25]

"reduce()": It applies a function of two arguments cumulatively to the elements of an iterable.

from functools import reduce

numbers = list(range(1,6))

product= reduce(lambda x,y: x*y, numbers)

print(product)

Output

120

"filter()": It creates a list of elements for which the function returns True.

numbers = list(range(1, 6))

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)

Output

[2, 4]

Remove Loops with Generator Expression


The Generators are a main type of Python function that allows you to create an iterable object, but they
generate the value according to the need, which can save memory while dealing with large data sets.

# Using a for loop to create a list of squares

squares = []

for n in range(50000):

[Link](n ** 2)

print(squares)

# Using a generator expression

# Reduced to 10 for brevity

squares_gen = (n ** 2 for n in range(50000))

for square in squares_gen:

print(square, end=' ')

Output:

Using for loop: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400,
441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521,
1600,...]

Using generator expression: 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400
441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600.........

What is the purpose of a loop?

In computer Programming, a Loop is used to execute a group of instructions or a block of code multiple
times, without writing it repeatedly. The block of code is executed based on a certain condition.

How to Use For Loops in Python: Step by Step


Written by Coursera • Updated on Feb 24, 2023

Share

By the end of this tutorial, you will be able to write and use for loops in various scenarios.

[Featured image] Two coders work on using for loop in python on a monitor and a laptop.

ow to Use For Loops in Python: Step by Step

How to Use For Loops in Python: Step by Step

Written by Coursera • Updated on Feb 24, 2023

Share

By the end of this tutorial, you will be able to write and use for loops in various scenarios.

[Featured image] Two coders work on using for loop in python on a monitor and a laptop.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE)
of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

For loops are control flow tools. They are used to iterate over objects or sequences—like lists, strings,
and tuples. You may use a for loop whenever you have a block of code you want to execute repeatedly.

How to Use For Loops in Python: Step by Step

How to Use For Loops in Python: Step by Step

Written by Coursera • Updated on Feb 24, 2023

Share

By the end of this tutorial, you will be able to write and use for loops in various scenarios.
[Featured image] Two coders work on using for loop in python on a monitor and a laptop.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE)
of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

For loops are control flow tools. They are used to iterate over objects or sequences—like lists, strings,
and tuples. You may use a for loop whenever you have a block of code you want to execute repeatedly.

Glossary

Term Definition

For loop An iterating function used to execute statements repeatedly.

Iterate In programming, iteration is the repetition of a code or a process until a specific condition is
met.

Iterables Iterables are objects in Python that you can iterate over.

Control flow Control flow or program flow, is the order of execution in a program’s code.

Control statements In Python, continue, break, and pass are control statements that change the
order of a program’s execution.

Indentation Indentation is the space at the beginning of each line of code. In Python, indentation
indicates a new line of code. In other programming languages, it is used only for readability purposes.

Tuple A tuple is an ordered set of values that is used to store multiple items in just one variable.

if if is a common conditional statement. It dictates whether a statement should be executed or


not by checking for a given condition. If the condition is true, the if block of code will be executed.

else The else statement contains the block of code that will execute if the condition from the if
statement is false or resolves to zero.

break The break command terminates the loop that contains it and redirects the program flow to the
following statement.

continue You can use the keyword continue to end a for loop’s current iteration and continue on
to the next.
pass In Python, pass does nothing. It can be used as a placeholder or to disregard code.

How to write a for loop in Python

Tell Python you want to create a for loop by starting the statement with for . ...

Write the iterator variable (or loop variable). ...

Use the keyword in . ...

Add the iterable followed by a colon. ...

Write your loop statements in an indented block

Why loop in Python?

The for loop in Python is used to iterate over a sequence (like a list, tuple or string) or other iterable
objects. Iterating over a sequence means going through each element one by one. In this article, we're
going to describe how to iterate over a Python list, using the built-in function for.

What is the syntax of for loop?

The for loop, written as [initial] [increment] [limit] { ... } for initializes an internal variable, and executes
the body as long as the internal variable is not more than the limit (or not less, if the increment is
negative) and, at the end of each iteration, increments the internal variable.

What are the three types of loops in Python?

In Python, there are three main types of loops: for , while , and nested loops. Let's dive into each of
them, along with their syntax and practical examples.

When to use for loop?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string). This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

What are the parts of a loop?

A loop has four parts. Initialization expression, Test expression, Update expression, The body of the
loop. for loop and while loop is known as Entry controlled loop and do-while loop is known as Exit
controlled loop.

What is a 'for-each' loop?


In computer programming, foreach loop (or for-each loop) is a control flow statement for traversing
items in a collection. foreach is usually used in place of a standard for loop statement.

What does "iterate" mean in programming?

An iteration is the execution of one, or many, lines of code more than once for a certain amount of
repetition (for) or until a condition is met (while)

Iteration: A single execution of the loop body. Infinite Loop: A loop that never terminates because the
condition is always true. (This is usually a bug!)

How is for loop executed?

A for loop has two parts: a header specifying the iteration, and a body which is executed once per
iteration. The header often declares an explicit loop counter or loop variable, which allows the body to
know which iteration is being executed.

Which loop is most used in Python?

In Python, the two most common loops are the For loop and the While loop. Both these loops help in
iteration but work differently and have different use cases

Which loop is mostly used?

for loop

The for loop is probably the most common and well known type of loop in any programming language.
For can be used to iterate through the elements of an array: For can also be used to perform a fixed
number of iterations: By default the increment is one.

How do you end a loop in Python?

You use the break statement in Python to immediately exit a loop, allowing the program to continue
executing the code that follows the loop.

What are common for loop errors?

Common Looping Errors

display the same output over and over again.

hang, which means that it just sits there and does nothing.

continue prompting the user forever and never letting them end the program.

What do while is an _______ loop?


The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true. Then it will repeat the loop as long as the condition is true.

What is each run of a loop called?

Loop Operation: the loop runs the body lines again and again, once for each element in the collection.
Each run of the body is called an "iteration" of the loop. For the first iteration, the variable is set to the
first element, and the body lines run (in this case, essentially num = 2 .

Which loop is faster in Python?

An implied loop in map() is faster than an explicit for loop; a while loop with an explicit loop counter is
even slower. Avoid calling functions written in Python in your inner loop. This includes lambdas. In-lining
the inner loop can save a lot of time.

What is a "while" loop in Python?

A while loop is a type of loop that repeats a block of code while a specific condition is true.

You might also like