# Async Basics — Python Fundamentals: From Basics to Async

Source: https://www.skillbyai.com/en/python/py-async-basics

> Run I/O-bound work concurrently with async, await and asyncio without threads.

## Why async?

`async`/`await` let a program work on other tasks while one is **waiting** — e.g. for a network response — instead of blocking everything.

## A minimal example

An `async def` function is a **coroutine**. `await` pauses it at a slow operation; `asyncio.run` starts the whole thing.

```python
import asyncio

async def fetch_data(name, delay):
    print(f"{name}: starting")
    await asyncio.sleep(delay)   # simulate I/O wait
    print(f"{name}: done")

async def main():
    await asyncio.gather(
        fetch_data("A", 2),
        fetch_data("B", 1),
    )

asyncio.run(main())
```

Output:

```
A: starting
B: starting
B: done
A: done
```

## Final quiz 1 of 8

Final quiz

**Quiz:** Which type is immutable?

- [ ] list
- [ ] dict
- [x] tuple
- [ ] set

*Answer:* tuple. Tuples cannot be changed after creation.

## Final quiz 2 of 8

Final quiz

**Quiz:** What does `[n*n for n in range(4)]` produce?

- [ ] [1, 4, 9, 16]
- [ ] [0, 1, 2, 3]
- [ ] [0, 2, 4, 6]
- [x] [0, 1, 4, 9]

*Answer:* [0, 1, 4, 9]. range(4) yields 0..3 and each is squared.

## Final quiz 3 of 8

Final quiz

**Quiz:** Why avoid `def f(x, items=[])`?

- [x] The list is created once and shared across calls
- [ ] It is a syntax error
- [ ] It is slower
- [ ] It cannot be called

*Answer:* The list is created once and shared across calls. Mutable defaults persist between calls; use None or a factory.

## Final quiz 4 of 8

Final quiz

**Quiz:** What does `with open(...) as f:` guarantee?

- [ ] The file is encrypted
- [x] The file is closed even if an error occurs
- [ ] The file is created
- [ ] The file is read-only

*Answer:* The file is closed even if an error occurs. Context managers run cleanup automatically.

## Final quiz 5 of 8

Final quiz

**Quiz:** What does `yield` do in a function?

- [ ] Ends the program
- [ ] Raises an exception
- [x] Produces a value lazily and pauses the function
- [ ] Returns a list

*Answer:* Produces a value lazily and pauses the function. Generators resume where they paused on the next call.

## Final quiz 6 of 8

Final quiz

**Quiz:** Which decorator creates an alternate constructor?

- [ ] @staticmethod
- [ ] @property
- [ ] @dataclass
- [x] @classmethod

*Answer:* @classmethod. A classmethod receives cls and can return a new instance.

## Final quiz 7 of 8

Final quiz

**Quiz:** Which keyword starts a coroutine?

- [x] async def
- [ ] yield def
- [ ] lambda
- [ ] class

*Answer:* async def. `async def` defines a coroutine you can await.

## Final quiz 8 of 8

Final quiz

**Quiz:** Which tool isolates a project's packages?

- [ ] os
- [x] venv
- [ ] sys
- [ ] math

*Answer:* venv. A virtual environment keeps dependencies per project.
