Log in from a computer to take this course

You'll need to log in from a computer to start Learn Advanced Python 3. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

Now we will cover another concurrent programming model: the asyncio module.

The asyncio module uses async/await syntax. async and await are two keywords that allow you to build and execute asynchronous code in your programs.

The async keyword declares a function as a coroutine. Coroutines are functions that may return normally with a value or may suspend themselves internally and return a continuation. This is a fancy way of saying they allow tasks to be paused and resumed to mimic multitasking. This is conceptually very similar to what we saw with threads! Coroutines are at the heart of asynchronous programs in Python.

The await keyword suspends execution of the current task until whatever is being “await”ed on is completed. For example, if we have an “await function task2” within a coroutine “task1” this tells Python “Suspend task1 until task2 is completed.”

Let’s apply this to some real examples and see how we declare asynchronous functions in Python. The following code block defines hello_async(), prints “hello”, waits three seconds, and prints “how are you?”.

import asyncio async def hello_async(): print("hello") await asyncio.sleep(3) print("how are you?")

To run the coroutine, we have to use the following syntax:

loop = asyncio.get_event_loop() loop.run_until_complete(hello_async())

Note: this syntax has been updated as of Python 3.7. It is now:

asyncio.run(hello_async)

We will have to use the longer syntax in this lesson and in future projects due to the Python version we run in our workspace. We apologize for this inconvenience.

Instructions

1.

Let’s change greeting_with_sleep_async() into an asynchronous function. To do this:

  • Add in the async keyword.
  • Replace time.sleep(2) with the await keyword.

Inside the terminal output, type python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running.

2.

Use the two lines of loop syntax noted in this lesson to run your asynchronous function. Call your function with string set equal to 'Codecademy'. What do you think the output will be?

Inside the terminal output, type python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?