Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

≀Paulo Portela
≀Paulo Portela

Posted on • Edited on

     

Python: A Guide to For and While Loops

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)
Enter fullscreen modeExit fullscreen mode
Output:12345678910
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:13579
Enter fullscreen modeExit fullscreen mode

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!")
Enter fullscreen modeExit fullscreen mode
Output:Exploring the universe!Exploring the universe!Exploring the universe!Exploring the universe!Exploring the universe!
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:15
Enter fullscreen modeExit fullscreen mode

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!")
Enter fullscreen modeExit fullscreen mode
Output:Number not found!
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode
Output:2
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:0 11 22 33 44 5
Enter fullscreen modeExit fullscreen mode

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}")
Enter fullscreen modeExit fullscreen mode
Output:Circle: 3.14Square: 4Rectangle: 6Triangle: 4.5
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:120
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode
Output:120
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Portugal
  • Education
    ISEP
  • Work
    Senior Software Developer @ adidas
  • Joined

More from≀Paulo Portela

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp