Loops in Python - Jupyter Notebook_52643069955dc0969f5fd149850a7462
Loops in Python - Jupyter Notebook_52643069955dc0969f5fd149850a7462
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.
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
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.
Lists in Python are ordered collections of elements. They are enclosed in square brackets
( [] ) and can contain elements of different data types.
Example:
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:
United States
Here, the loop will print "United States" only when that country is encountered in the list.
In Python, you can easily iterate over each character in a string using a for loop. The loop
processes each character one by one.
H
e
l
l
o
In this example, the loop will print each character of the string "Hello" on a new line.
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:
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:
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:
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.
0
1
2
3
4
5
You can also check the type of the range() function, which returns a range object.
<class 'range'>
Example:
0 1 2 3 4 5 6 7 8 9
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:
10 11 12 13 14 15
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:
10
8
6
4
2
The range() function works only with integers. You cannot use float or other data types
as the start, stop, or step values.
The step value must not be zero. If step=0 , Python will raise a ValueError .
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:
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:
Printing Patterns
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?
* * * * *
* * * * *
How can we print a vertical line of five stars, with each star on a new line, using a for loop in
Python?
*
*
*
*
*
*
*
*
*
*
How can we print five lines, each containing five stars, using a for loop in Python?
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
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?
*
* *
* * *
* * * *
* * * * *
*
* *
* * *
* * * *
* * * * *
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()
* * * * *
* * * *
* * *
* *
*