> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Basic Code Completion

> This tutorial explores how GitHub Copilot accelerates common Python workflows with examples of generating boilerplate, implementing algorithms, and handling data structures.

In this tutorial, we’ll explore how GitHub Copilot accelerates common Python workflows. You’ll see examples of generating boilerplate, implementing algorithms, handling data structures, managing errors, and making HTTP requests—all with minimal typing.

## Table of Contents

* [1. Setup: Creating the Python File](#1-setup-creating-the-python-file)
* [2. Hello, World!](#2-hello-world)
* [3. Factorial Function](#3-factorial-function)
* [4. List Comprehension Example](#4-list-comprehension-example)
* [5. File I/O with Exception Handling](#5-file-io-with-exception-handling)
* [6. HTTP Requests with the `requests` Library](#6-http-requests-with-the-requests-library)
* [Conclusion & Key Takeaways](#conclusion--key-takeaways)
* [Links and References](#links-and-references)

***

## 1. Setup: Creating the Python File

First, open your terminal and create a new script named `main.py`:

```bash theme={null}
touch main.py
```

Then open **main.py** in your preferred editor and trigger Copilot suggestions by starting to type.

***

## 2. Hello, World!

Start by asking Copilot to scaffold the classic “Hello, World!” program:

```python theme={null}
def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()
```

Save and run:

```bash theme={null}
python3 main.py
# Output:
# Hello, World!
```

Copilot handles the boilerplate so you can jump straight to running your code.

***

## 3. Factorial Function

### 3.1 Complete from the Signature

Type the function signature, and Copilot will fill in the implementation:

```python theme={null}
def factorial(n: int) -> int:
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
```

### 3.2 Guide with a Docstring

Alternatively, add a descriptive docstring to guide Copilot:

```python theme={null}
def factorial(n: int) -> int:
    """Return the factorial of a non-negative integer."""
```

Copilot may then suggest:

```python theme={null}
def factorial(n: int) -> int:
    """Return the factorial of a non-negative integer."""
    if n == 0:
        return 1
    return n * factorial(n - 1)
```

You can invoke it from `main()` or any other part of your script.

***

## 4. List Comprehension Example

Imagine you have a list of user dictionaries:

```python theme={null}
users = [
    {"name": "Michael", "id": 1},
    {"name": "Sanjeev",  "id": 2},
    {"name": "Jeremy",   "id": 3}
]
```

Start typing:

```python theme={null}
usernames = 
```

Copilot suggests:

```python theme={null}
usernames = [user["name"] for user in users]
```

Print them with:

```python theme={null}
for username in usernames:
    print(username)
```

Run to see the output:

```bash theme={null}
python3 main.py
# Michael
# Sanjeev
# Jeremy
```

***

## 5. File I/O with Exception Handling

When working with file operations, Copilot can quickly generate a `try/except` block.

```python theme={null}
try:
    with open("data.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    data = "No data available"

print(data)
```

If **data.txt** is missing:

```bash theme={null}
python3 main.py
# No data available
```

<Callout icon="lightbulb" color="#1CB2FE">
  For very large files, consider reading in chunks or using `file.readline()` to avoid high memory usage.
</Callout>

To catch all exceptions and log error details:

```python theme={null}
try:
    with open("data.txt", "r") as f:
        data = f.read()
except Exception as e:
    print(f"Error reading file: {e}")
    data = "default data"

print(data)
```

***

## 6. HTTP Requests with the `requests` Library

### 6.1 Installing and Importing

Type and let Copilot complete:

```python theme={null}
import requests
```

If you haven’t installed it yet:

```bash theme={null}
pip install requests
```

### 6.2 Making a GET Request

Copilot suggests the typical pattern:

```python theme={null}
response = requests.get("https://api.github.com")
print(response.status_code)
```

### 6.3 Handling Request Errors

Use Copilot to scaffold robust error handling:

```python theme={null}
try:
    response = requests.get("https://api.github.com")
    response.raise_for_status()
    print(response.json())
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
```

<Callout icon="triangle-alert" color="#FF6B6B">
  Always validate or sanitize external data returned from HTTP calls to prevent security issues.
</Callout>

***

## Conclusion & Key Takeaways

GitHub Copilot streamlines your Python development by:

* Automating boilerplate code
* Reducing syntax errors and runtime bugs
* Suggesting idiomatic patterns (comprehensions, recursion, error handling)
* Assisting with package installation and debugging

| Task                    | Copilot Prompt Example              | Benefit                   |
| ----------------------- | ----------------------------------- | ------------------------- |
| Hello, World!           | Type `def main():`                  | Instant program scaffold  |
| Recursive algorithms    | Add `def factorial(n: int) -> int:` | Correct recursive logic   |
| List comprehensions     | Start `usernames = [`               | Compact data extraction   |
| File I/O error handling | Begin `try:`                        | Robust file operations    |
| HTTP requests & errors  | Type `import requests`              | Reliable API interactions |

Master these patterns to focus on solving complex problems instead of writing repetitive code.

***

## Links and References

* [GitHub Copilot](https://github.com/features/copilot)
* [Python Official Website](https://www.python.org/)
* [requests Library Documentation](https://docs.python-requests.org/en/latest/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/github-copilot-certification/module/b02a5227-ee17-43dc-b006-51fef8272f13/lesson/73b6deac-6b87-4d73-9321-85cf364cb833" />
</CardGroup>
