0% found this document useful (0 votes)
5 views

Loops in Python - Jupyter Notebook_52643069955dc0969f5fd149850a7462

The document provides a comprehensive overview of loops in Python, focusing on for loops and while loops. It explains how to iterate over various data structures such as lists and strings, introduces the enumerate() function for indexing, and discusses the range() function for generating sequences of numbers. Additionally, it covers nested loops and provides examples of printing patterns using loops.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Loops in Python - Jupyter Notebook_52643069955dc0969f5fd149850a7462

The document provides a comprehensive overview of loops in Python, focusing on for loops and while loops. It explains how to iterate over various data structures such as lists and strings, introduces the enumerate() function for indexing, and discusses the range() function for generating sequences of numbers. Additionally, it covers nested loops and provides examples of printing patterns using loops.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Loops in Python

Loops are programming constructs that allow you to repeat a block of code multiple times.
Python provides two main types of loops: for loops and while loops.

for Loop

A for loop in Python is used to iterate over a sequence of items or perform a set of operations
a specific number of times. It allows you to loop through elements in an iterable, such as a list
or string, and perform actions on each element in turn.

Looping through an Iterable

An iterable is an object that can return its elements one at a time, allowing you to iterate over
them. Examples of iterables in Python include lists, tuples, sets, dictionaries, and strings. In
simpler terms, an iterable is anything that you can loop through.

Syntax

for item in iterable:


# Code to be executed in each iteration

item: A variable that takes the value of each element in the iterable, one at a time, during
each iteration of the loop.
iterable: A collection of items (e.g., a list, tuple, or string) that you want to iterate over.

The code inside the for loop will be executed once for each item in the iterable.

Iterate over a list

Lists in Python are ordered collections of elements. They are enclosed in square brackets
( [] ) and can contain elements of different data types.

Example:

In [1]: my_list = [1, "hello", 3.14, True]

In this example, my_list is a list containing an integer, a string, a float, and a boolean value.

You can use a for loop to iterate over each element in a list. For example, consider the
following list of countries:
In [2]: countries = ['United States', 'India', 'China', 'Brazil']
for country in countries:
print(country)

United States
India
China
Brazil

In this case, the for loop will go through each country in the list and print it.

You can also use a conditional inside the loop to perform actions based on specific values. For
example:

In [3]: for country in countries:


if country == "United States":
print(country)

United States

Here, the loop will print "United States" only when that country is encountered in the list.

Iterate over a String

In Python, you can easily iterate over each character in a string using a for loop. The loop
processes each character one by one.

In [4]: message = "Hello"


for i in message:
print(i)

H
e
l
l
o

In this example, the loop will print each character of the string "Hello" on a new line.

Enumerating in a for loop

In Python, the enumerate() function is used in for loops to iterate over both the elements
and their corresponding indices (positions) in an iterable (e.g., a list, tuple, or string).

It returns an enumerator object, which produces a tuple containing the index and the value
from the iterable in each iteration. This is particularly useful when you need to keep track of the
position of items while iterating through a sequence.
Basic Syntax:

for index, item in enumerate(iterable):


# Code to be executed for each iteration

index: A variable that stores the index of the current item in the iteration.
item: The actual value from the iterable at the current index.

Example:

In [5]: countries = ['United States', 'India', 'China', 'Brazil']


for i, country in enumerate(countries):
print(i, country)

0 United States
1 India
2 China
3 Brazil

In this example, the enumerate() function helps to print both the index ( i ) and the
corresponding country ( country ) from the countries list.

range() function

The range() function is a built-in Python function used to generate a sequence of numbers. It
is often utilized in for loops to iterate over a specific range of values. The function can take
one, two, or three arguments and returns an iterable sequence of numbers.

Parameters:

start (optional): Specifies the starting point of the sequence. The default value is 0 if not
provided.
stop (mandatory): Specifies the endpoint of the sequence (exclusive). The sequence will
include numbers up to, but not including, this value.
step (optional): Specifies the interval between each number in the sequence. The default
value is 1 if not provided. A negative step can be used to generate a sequence in
descending order.
Basic Syntax:

range(stop) # Creates a range starting from 0 to stop-


1
range(start, stop) # Creates a range from start to stop-1
range(start, stop, step) # Creates a range from start to stop-1, w
ith a step increment/decrement

1. Creating a Range with Only the Stop Value:

If only the stop value is provided, the range starts at 0 and increments by 1 until it reaches (but
does not include) the stop value.

In [6]: # range(6) --> Creates a range from 0 to 5



for i in range(6):
print(i)

0
1
2
3
4
5

You can also check the type of the range() function, which returns a range object.

In [7]: print(type(range(10))) # Output: <class 'range'>

<class 'range'>

Example:

Print the first 10 numbers in one line:

In [8]: for i in range(10):


print(i, end=' ')

0 1 2 3 4 5 6 7 8 9

2. Creating a Range with Start and Stop Values:

You can specify both the start and stop values. The range starts from the start value and goes
up to (but does not include) the stop value.
In [9]: for i in range(2, 6): # Creates a range from 2 to 5
print(i)

2
3
4
5

Example:

Print numbers from 10 to 15:

In [10]: for i in range(10, 16):


print(i, end=' ')

10 11 12 13 14 15

3. Creating a Range with Start, Stop, and Step Values:

You can also specify a step value to control the increment between numbers.

In [11]: for i in range(10, 50, 5): # Creates a range from 10 to 45, incrementing by 5
print(i, end=' ')

10 15 20 25 30 35 40 45

Example:

Print odd numbers between 1 and 10:

In [12]: for i in range(1, 10, 2):


print("Current value of i is:", i)

Current value of i is: 1


Current value of i is: 3
Current value of i is: 5
Current value of i is: 7
Current value of i is: 9

4. Using a Negative Step:

Here, the sequence starts at 10 and decrements by 2 down to 2 (stop+1).


In [13]: for i in range(10, 1, -2):
print(i)

10
8
6
4
2

Points to remember about range() function

The range() function works only with integers. You cannot use float or other data types
as the start, stop, or step values.

All three arguments (start, stop, step) can be positive or negative.

The step value must not be zero. If step=0 , Python will raise a ValueError .

Nested for loops

Nested for loops are loops that are contained within other loops. They allow you to iterate
over multiple sequences or perform repetitive tasks within repetitive tasks.

Syntax:

for outer_element in outer_sequence:


for inner_element in inner_sequence:
# Code to be executed

Example:
In [14]: outer_list = [1, 2, 3]
inner_list = ["a", "b", "c"]

for outer_element in outer_list:
for inner_element in inner_list:
print(outer_element, inner_element)

1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c

Explanation:

1. The outer for loop iterates over the outer_list .


2. For each element in the outer_list , the inner for loop iterates over the inner_list .
3. The code inside the nested loop (in this case, the print statement) is executed for each
combination of elements from the outer and inner lists.

Printing Patterns

1. Printing a Straight Line of Stars

First, let’s print a single line of stars. How can we print a single line of five stars using a for
loop in Python?

* * * * *

In [15]: # Write your code below.



for i in range(5):
print("*", end=" ")

* * * * *

2. Printing a Vertical Line of Stars

How can we print a vertical line of five stars, with each star on a new line, using a for loop in
Python?
*
*
*
*
*

In [16]: # Write your code below.



for i in range(5):
print("*")

*
*
*
*
*

3. Printing Multiple Lines of Stars

How can we print five lines, each containing five stars, using a for loop in Python?

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

In [17]: # Write your code below.



for i in range(5):
for j in range(5):
print("*", end=" ")
print()

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Basic Concepts:
Outer Loop: Controls the number of rows.
4. Printing a Right-Angled Triangle of Stars

How can we modify the above code to print a right-angled triangle pattern of stars, with each
row containing an increasing number of stars?

*
* *
* * *
* * * *
* * * * *

In [18]: # Write your code below.



for i in range(5):
for j in range(i + 1):
print("*", end=" ")
print()

*
* *
* * *
* * * *
* * * * *

5. Printing an Inverted Triangle of Stars

What changes would you make to the code above to print an inverted right-angled triangle
pattern of stars, where the first row contains the maximum number of stars, and each following
row has one less star than the previous?

* * * * *
* * * *
* * *
* *
*
In [19]: # Write your code below.

for i in range(5):
for j in range(5 - i):
print("*", end=" ")
print()

* * * * *
* * * *
* * *
* *
*

You might also like