Basic Loops in Python
This article explains how to use ‘for’ and ‘while’ statements to create loops in Python, each serving different purposes for repetitive tasks. The article also explores additional control statements such as ‘break,’ ‘continue,’ ‘pass,’ and ‘else’ to manage loop execution.
In Python, the major statements required to create loops are ‘for’ and ‘while’.The for statement is mostly used to iterate over iterable objects (such as a string, tuple, or list). Additionally, like other coding languages (Python Software Foundation (a), n.d.). The ‘while’ loop, on the other hand, is used for repeated execution as long as an expression is true. (Python Software Foundation (b), n.d.).
In other words, both the ‘for’ and the ‘while’ loops are algorithmic, meaning they perform repetitive tasks until a condition is met or a condition remains true. To be more specific, the ‘for’ iterates over sequences executing a set of instructions until a condition is met, for example, until the end of the sequence is reached. In comparison, the ‘while’ will execute a set of instructions as long a condition is true. The loops complement each other and when nested within each other they can be a powerful tool for solving complex problems. This is the main reason Python has more than one loop statement.
The ‘for’ statementThe ‘for’ statement goes through each item in the sequence or iterable, one by one, and executes the block of code for each element. The flow chart below depicts the algorithmic nature of the ‘for’ loop.
Figure 1
The ‘for’ loop
Note: 4.3 For Loops in Python, by Colorado State University Global (2024a)
A scenario of iterating over a sequence using a ‘for’ loop could be similar to the following:
user_ids = [101, 102, 103, 104] for user_id in user_ids: print (user_id)
The ‘while’ statementThe ‘while’ statement, before each iteration, evaluates the condition; if the condition is true, the loop’s body is executed. If the condition becomes false, the loop stops. The flow chart below depicts the algorithmic nature of the ‘while’ loop.
Figure 2
The ‘while’ loop
_
Note: from 4.2 While Loops in Python, by Colorado State University Global (2024b)
A scenario of iterating using a ‘while’ loop as long a condition is true could be similar to the following:
user_ids = [101, 102, 103, 104] for user_id in user_ids: print (user_id)
The ‘break’ will exit the loop. The ‘break’, ‘continue’, ‘pass’, and ‘else’ statements can be used in conjunction with loops to control their execution.
- The ‘break’ statement is used within loops to exit the loop.
- The ‘continue’ statement allows the loop to skip the rest of its code block and proceed directly to the next iteration.
- The ‘pass’ statement acts as a placeholder and does nothing really. It is often used by programmers as a placeholder to bypass blocks of code that are under construction or not yet implemented.
- The ‘else’ statement executes a block of code after the loop completes normally. In other words, the code within the ‘else’ block runs only if the loop is not terminated by a ‘break’ statement.
For example, the ‘while’ loop example could be rewritten as follows:
coffee = 0 homework_num = 100 while coffee < 100: coffee += 1 print(f"Drinking coffee number {coffee} ...") if coffee < 100: print(f"Doing homework number {homework_num } …") homework_num -= 1 if homework_num == 0: break else: print("Rest in peace!")
Here the ‘else’ statement is part of the ‘while’ loop, the code within the ‘else’ would be executed if the loop is not terminated by the ‘break’ statement. In this case, the code within the ‘else’ statement will run.
In conclusion, Python’s ‘for’ and ‘while’ loops, along with control statements like ‘break,’ ‘continue,’ ‘pass,’ and ‘else,’ allow for control and flexibility in managing repetitive tasks in programming and creating effective code.
References:
Colorado State University Global (2024a) 4.3 For Loops in Python. Module 4: Python. Repetition. In ITS320: Basic Programming.
Colorado State University Global (2024b) 4.2 While Loops in Python. Module 4: Python. Repetition. In ITS320: Basic Programming.
Python Software Foundation (a). (n.d.). 4. More Control Flow Tools. The Python Tutorial. python.org. https://docs.python.org/3/tutorial/controlflow.html#index-0Links to an external site.
Python Software Foundation (b). (n.d.). 8. Compound statements. T_he Python Language Reference_. python.org. https://docs.python.org/3/tutorial/controlflow.html#index-0
Originally published at Basic Loops in Python - Medium on August 19, 2024.
The above is the detailed content of Basic Loops in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
