A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_await_keyword.htm below:

Python await Keyword

Python await Keyword

The Python await keyword is used to pause a coroutine. The coroutine is a function with the ability to pause its execution when encountering an operation that may take a while to complete.

When the long-running operation completes, we can resume the paused coroutine and execute the remaining code in that coroutine.While the coroutine is waiting for the long-running operation, we can run other code. By doing this, we can run the program asynchronously to improve its performance.

Syntax

Following is the syntax of the Python await keyword −

await
Example

Following is an basic example of the Python await keyword −

import asyncio
# Define the asynchronous function
async def cube(number):
    return number * number * number
# Main function to run the coroutine
async def main():
    # Await the result of the cube function
    result = await cube(10)
    print(result)
# Run the main function
asyncio.run(main())
Output

Following is the output of the above code −

1000
Using 'await' with sleep()

The sleep() is used to pause the execution for mentioned section. It accepts an integers value.

Example

Here, we have paused the function for one second using sleep() and await keyword −

import asyncio
async def say_hello():
    print("Hello!")
    await asyncio.sleep(1)  # Pauses the execution for 1 second
    print("World!")
async def main():
    print("Start")
    await say_hello()  # Waits for the say_hello coroutine to complete
    print("End")
# Run the main coroutine
asyncio.run(main())

Output

Following is the output of the above code −

Start
Hello!
World!
End

python_keywords.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4