Introduction
In this chapter, we'll explore the use of for and while loops in Python. We'll start by showing how to create a loop using therange
function, which allows us to iterate over a sequence of numbers. For example, we can userange
to create a loop that prints the numbers 1 to 10:
foriinrange(1,11):print(i)
Output:12345678910
Using Range with Specific Intervals
We can also userange
to create a loop that iterates over a specific interval, such as every other number between 1 and 10:
foriinrange(1,11,2):print(i)
Output:13579
Using the Underscore as a Placeholder Variable
In Python, we can use an underscore (_
) as a placeholder variable when we don't need the value of the variable in the loop. For example, if we want to repeat an action 5 times, we can use a for loop with an underscore as the loop variable:
for_inrange(5):print("Exploring the universe!")
Output:Exploring the universe!Exploring the universe!Exploring the universe!Exploring the universe!Exploring the universe!
Iterating Through a List
We can also use a for loop to iterate through a list. For example, let's say we have a list of numbers, and we want to calculate the sum of these numbers:
numbers=[1,2,3,4,5]total=0fornumberinnumbers:total+=numberprint(total)
Output:15
Using the Else Statement in a For Loop
We can use theelse
statement in a for loop to specify a block of code to be executed when the loop has finished iterating. For example, let's say we want to search for a specific number in our list of numbers, and print a message when we find it:
numbers=[1,2,3,4,5]fornumberinnumbers:ifnumber==6:print("Number found!")breakelse:print("Number not found!")
Output:Number not found!
In this example, theelse
block is executed because thebreak
statement is never reached, meaning that the loop completed all iterations without finding the number 6.
Using the Break Statement
We can use thebreak
statement to exit a loop prematurely. For example, let's say we want to search for the first even number in our list of numbers:
numbers=[1,2,3,4,5]fornumberinnumbers:ifnumber%2==0:print(number)break
Output:2
In this example, thebreak
statement is used to exit the loop as soon as the first even number is found.
Using the Enumerate Function
We can use theenumerate
function to iterate through a list and keep track of the index of each element. For example, let's say we want to print the index and value of each number in our list:
numbers=[1,2,3,4,5]fori,numberinenumerate(numbers):print(i,number)
Output:0 11 22 33 44 5
Using the Zip Function
We can use thezip
function to iterate over two or more lists in parallel. For example, let's say we have two lists, one containing the names of shapes and another containing their areas, and we want to print the name and area of each shape:
shapes=["Circle","Square","Rectangle","Triangle"]areas=[3.14,4,6,4.5]forshape,areainzip(shapes,areas):print(f"{shape}:{area}")
Output:Circle: 3.14Square: 4Rectangle: 6Triangle: 4.5
Using List Comprehension
List comprehension is a concise way to create lists. For example, let's say we want to create a list of the squares of the numbers from 1 to 10:
squares=[x**2forxinrange(1,11)]print(squares)
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Using While Loops
We can also use a while loop to iterate while a certain condition is true. For example, let's say we want to calculate the factorial of a number using a while loop:
n=5factorial=1whilen>1:factorial*=nn-=1print(factorial)
Output:120
Using the Walrus Operator
In Python 3.8, a new feature called the "walrus operator" (:=
) was introduced, which allows us to assign values to variables as part of an expression. For example, let's say we want to calculate the factorial of a number using a while loop and the walrus operator:
n=5factorial=1while(n:=n-1)>0:factorial*=n+1print(factorial)
Output:120
In this example, the walrus operator is used to decrement the value ofn
by 1 and assign the result back ton
as part of the condition in the while loop.
Conclusion
For and while loops are essential tools for controlling the flow of a program in Python. They provide a flexible and versatile way to iterate over sequences and repeat actions, allowing us to solve complex problems with ease.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse