Printing numbers with a delay using asyncio coroutines in Python
Python Asynchronous: Exercise-3 with Solution
Write a Python program that creates an asyncio event loop and runs a coroutine that prints numbers from 1 to 7 with a delay of 1 second each.
Sample Solution:
Code:
import asyncio
async def display_numbers():
for i in range(1, 8):
print(i)
await asyncio.sleep(1)
# Run the coroutine using asyncio.run()
asyncio.run(display_numbers())
Output:
1 2 3 4 5 6 7
Explanation:
In the above exercise-
The "display_numbers()" function is an asynchronous coroutine. It uses the 'await' keyword to introduce a pause using await asyncio.sleep(1) after printing each number. This 'sleep()' function introduces a 1 second delay.
The asyncio.run() function runs the “display_numbers()” coroutine. This function is introduced in Python 3.7 and provides a simple and clean way to run an asynchronous function in an event loop.
- Inside the event loop created by asyncio.run(), the display_numbers() coroutine is executed.
- For each iteration of the loop (from 1 to 7), the current number is displayed, and then the coroutine is paused for 1 second using await asyncio.sleep(1).
Flowchart:
Previous: Running asynchronous Python functions with different time delays.
Next: Fetching data asynchronously from multiple URLs using Python async IO.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/asynchronous/python-asynchronous-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics