Sling Academy
Home/Python/Python: Using async/await with loops (for & while loops)

Python: Using async/await with loops (for & while loops)

Last updated: July 10, 2023

This concise, practical article will walk you through some examples that showcase different scenarios for using the async and await keywords with for loops and while loops in Python, from basic asynchronous loops to parallel execution, rate limiting, and external termination conditions.

Basic Example: Asynchronous Loop

In this basic example, we define an async function countdown() that prints numbers from 1 to 10 asynchronously using await and asyncio.sleep(). We use a for loop to iterate through the numbers and await the sleep operation to introduce a delay of one second between each number.

import asyncio

async def countdown():
    for i in range(1, 11):
        print(i)
        await asyncio.sleep(1)

async def main():
    await countdown()

asyncio.run(main())

Parallel Execution with Gather

This example demonstrates running multiple coroutines concurrently using asyncio.gather() and an async loop. We’ll define a coroutine countdown() (it isn’t the same as the one in the preceding example) that prints numbers with a delay. Inside the main() function, we create tasks for each coroutine using asyncio.create_task() and use asyncio.gather() to wait for all tasks to complete.

import asyncio

async def countdown(n):
    for i in range(1, n + 1):
        print(i)
        await asyncio.sleep(1)

async def main():
    tasks = [
        asyncio.create_task(countdown(10)),
        asyncio.create_task(countdown(7)),
    ]
    await asyncio.gather(*tasks)

asyncio.run(main())

Looping with Rate Limiting

This example showcases an async loop with rate limiting using asyncio.sleep() to control the frequency of execution. We define a coroutine process_item() that processes each item with a delay. Inside the main() function, we iterate over a list of items and await the execution of process_item() with a sleep interval between each iteration.

import asyncio

async def process_item(item):
    print(f"Processing item: {item}")
    await asyncio.sleep(1)

async def main():
    items = [1, 2, 3, 4, 5]
    for item in items:
        await process_item(item)

        # Rate limit between iterations
        await asyncio.sleep(0.5)  

asyncio.run(main())

Looping with External Termination Condition

This example demonstrates an async loop with an external termination condition. We define a coroutine countdown() that prints numbers with a delay. Inside the main() function, we use a while loop with an external condition (count) to determine when to stop the loop.

import asyncio

async def countdown():
    count = 5
    while count > 0:
        print(count)
        await asyncio.sleep(1)
        count -= 1

async def main():
    await countdown()

asyncio.run(main())

Conclusion

The examples in this article demonstrate how async/await can be used effectively with loops to handle various situations in asynchronous programming. If you have any questions related to this topic, please comment. Happy coding & have a nice day!

Next Article: Python async/await and timeouts (with examples)

Previous Article: Python asyncio.run() function (with examples)

Series: Python Asynchronous Programming Tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots