Logo
  • Ubuntu
  • CentOS
  • Debian
  • Fedora
  • RedHat

Python For Loop - DesignLinux

designlinux 0 Comments

Loops are one of the fundamental concepts of programming languages. Loops are used to perform repeated tasks until a certain condition is met.

There are two main looping constructs in Python that allow you to repeat a block of code repeatedly, the for and the while loops.

In this article, we will cover the basics of the for loops in Python. We will also show you how to use the range type to generate a sequence of numbers, and else, break and continue statements to alter the flow of a loop.

Python for Loop #

The for loop in Python iterates over the items of a sequence and repeatedly executes a block of statements.

The Python for loop takes the following form:

for item in sequence:
  statements

The for statement starts with the for keyword, then a variable (item) to assign each item of the sequence to (loop control target), followed by the in keyword, and finally the sequence. Each conditional statement ends with a colon (:).

The statements block starts with an indentation and ends with the first unindented line. Most people choose to use either 4-space or 2-space indentation. The official Style Guide for Python Code recommends to use 4-spaces per indentation level and to avoid mixing the use of tabs and spaces for indentation.

Here is an example:

berries = ["Blueberry", "Raspberry", "Strawberry"]

for berry in berries:
  print(berry)
Blueberry
Raspberry
Strawberry

You can iterate over any sequence such as a string, a list, a dictionary, or a tuple.

In the code below, we’re iterating through the characters in the string ‘linux’:

for x in 'linux':
  print(x)
l
i
n
u
x

When looping through a dictionary, the variable is assigned to the key:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for key in berries:
  print(key)
Blueberry
Raspberry
Strawberry

To access the values of the dictionary, use the key’s index:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for key in berries:
  print(berries[key])

Another option to loop trought the dictionary’s values is to use the values() method:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for value in berries.values():
  print(value)

The output of both examples is the same:

100
125
150

The range() Constructor #

The Python range() constructor allows you to generate a sequence of integers by defining the start and the end point of the range. range() works differently in Python 2 and 3. In this article, we are using Python 3.

range() is typically used with the for loop to iterate over a sequence of numbers. This is a Python equivalent of the C-style for loop.

When only one argument is given, range returns a sequence of numbers, incremented by 1, starting from 0 to argument - 1:

for i in range(3):
  print(i)
0
1
2

When two arguments are provided, range returns a sequence of numbers, incremented by 1, starting from the first argument to second argument - 1:

for i in range(3, 5):
  print(i)
3
4

The third argument allows you to specify an increment:

for i in range(0, 16, 5):
  print(i)
0
5
10
15

Nested for Loop #

A nested loop is a loop inside another loop. They are often used to handle iterable object that contains iterable elements:

for i in range(0, 6):
  for j in range(0, 6):
    print('%d + %d = %d' % (i, j, i+j))
0 + 0 = 0
0 + 1 = 1
0 + 2 = 2
...
5 + 3 = 8
5 + 4 = 9
5 + 5 = 10

The break and continue Statements #

The break and continue statements allow you to control the execution of the for loop.

break Statement #

The break statement terminates the current loop and passes the program control to the statement that follows the loop. When used inside a nested loop, the break statement terminates the innermost loop.

In the following example, we are using the if statement to terminate the execution of the loop once the current iterated item is equal to ‘Raspberry’:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  if i == "Raspberry":
    break
  print(i)
Blueberry

continue Statement #

The continue statement exits the current iteration of the loop and passes the program control to the next iteration of the loop. The loop is not terminated; only the current iteration is skipped.

In the following example, we are iterating through a range of numbers. When the current iterated item is equal to ‘3’, the continue statement will cause execution to return to the beginning of the loop and to continue with the next iteration:

for i in range(1, 6):
  if i == 3:
    continue
  print(i)
1
2
4
5

The else Clause #

In Python, the for loop can have an optional else clause.

The else clause is executed when the loop finishes normally, i.e when all iterables are exhausted:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  print(i)
else:
  print('Loop completed.')
Blueberry
Raspberry
Strawberry
Loop completed.

When the loop is terminated with break or continue statements, the else clause is not executed:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  if i == "Raspberry":
    break
  print(i)
else:
  print('Loop completed.')
Blueberry

Conclusion #

The Python for loop is used to repeatedly execute a block of code for a fixed number of times.

If you have any questions or feedback, feel free to leave a comment.

python loop

Related

Tags: loop, python

4 Open Source Log Monitoring and Management Tools for Linux

Prev Post

How To Prevent PHP-FPM From Consuming Too Much RAM in Linux

Next Post
Archives
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
Categories
  • AlmaLinux
  • Android
  • Ansible
  • Apache
  • Arch Linux
  • AWS
  • Backups
  • Bash Shell
  • Bodhi Linux
  • CentOS
  • CentOS Stream
  • Chef
  • Cloud Software
  • CMS
  • Commandline Tools
  • Control Panels
  • CouchDB
  • Data Recovery Tools
  • Databases
  • Debian
  • Deepin Linux
  • Desktops
  • Development Tools
  • Docker
  • Download Managers
  • Drupal
  • Editors
  • Elementary OS
  • Encryption Tools
  • Fedora
  • Firewalls
  • FreeBSD
  • FTP
  • GIMP
  • Git
  • Hadoop
  • HAProxy
  • Java
  • Jenkins
  • Joomla
  • Kali Linux
  • KDE
  • Kubernetes
  • KVM
  • Laravel
  • Let's Encrypt
  • LFCA
  • Linux Certifications
  • Linux Commands
  • Linux Desktop
  • Linux Distros
  • Linux IDE
  • Linux Mint
  • Linux Talks
  • Lubuntu
  • LXC
  • Mail Server
  • Manjaro
  • MariaDB
  • MongoDB
  • Monitoring Tools
  • MySQL
  • Network
  • Networking Commands
  • NFS
  • Nginx
  • Nodejs
  • NTP
  • Open Source
  • OpenSUSE
  • Oracle Linux
  • Package Managers
  • Pentoo
  • PHP
  • Podman
  • Postfix Mail Server
  • PostgreSQL
  • Python
  • Questions
  • RedHat
  • Redis Server
  • Rocky Linux
  • Security
  • Shell Scripting
  • SQLite
  • SSH
  • Storage
  • Suse
  • Terminals
  • Text Editors
  • Top Tools
  • Torrent Clients
  • Tutorial
  • Ubuntu
  • Udemy Courses
  • Uncategorized
  • VirtualBox
  • Virtualization
  • VMware
  • VPN
  • VSCode Editor
  • Web Browsers
  • Web Design
  • Web Hosting
  • Web Servers
  • Webmin
  • Windows
  • Windows Subsystem
  • WordPress
  • Zabbix
  • Zentyal
  • Zorin OS
Visits
  • 1
  • 604
  • 1,055,376

DesignLinux.com © All rights reserved

Go to mobile version