# Python 2 - Your First Python Project: From Empty Folder to Working Code

## Part 1: Aman Starts a Real Project

In the last article, Aman learned how Python works inside. Now he wants to *build* something. He opens his laptop, creates a file on the desktop called `test.py`, and starts typing.

Neha stops him. "No. Not on the desktop. Not a random file. If you want to build AI apps later, you must learn to work like a professional from day one. Projects, environments, packages. Let's do it properly."

Aman sighs. "Is it a lot of work?"

"Ten minutes," says Neha. "And you will never be confused again."

This article covers:

1. Creating your first project folder and VS Code workspace
2. Writing and running `hello.py`
3. Python environments, `venv`, `pip`, and `import`
4. Comments
5. Numbers, strings, f-strings, and string methods
6. Booleans and operators
7. `if / elif / else`
8. `for` loops and `range()`
9. Lists, dictionaries, tuples, and sets

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/901d075c-3a10-4f86-bbfe-e2b7c6022b18.png align="center")

---

## Part 2: Creating Your First Project

A **project** is just a folder. But it is a folder with a purpose: everything for one piece of work lives inside it.

### Step 1: Make a folder

Neha tells Aman to create a folder called `python-course` somewhere sensible, for example:

- Windows: `C:\Users\Aman\projects\python-course`
- Mac/Linux: `/Users/aman/projects/python-course`

Keep the name simple. Use lowercase. Use hyphens (`-`) or underscores (`_`) instead of spaces. Spaces in folder names cause problems in the terminal later.

### Step 2: Open the folder in VS Code

Open VS Code. Go to **File → Open Folder** and choose `python-course`.

Now VS Code treats this folder as your **workspace**. The left sidebar (the Explorer) shows your files. The built-in terminal opens *inside* this folder. Everything you do stays in one place.

### Step 3: Save the workspace (optional but useful)

VS Code can save your folder as a workspace file. Go to **File → Save Workspace As…** and save it inside the folder. Next time, you can open this workspace with one click.

Neha's rule: **One project = one folder = one VS Code window.**

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/6f845ed5-6e3a-4456-af8e-b98331a98d7b.png align="center")

---

## Part 3: Your First Python File ([hello.py](http://hello.py))

In the VS Code Explorer, Aman clicks **New File** and names it `hello.py`.

Two things matter here:

- The name should be lowercase (`hello.py`, not `Hello.py`).
- The extension must be `.py`. This tells VS Code and Python that this is a Python file.

Inside the file, he writes:

```python
print("Hello, world!")
```

That is a complete Python program. One line.

### What is `print()`?

`print()` is a **function**. A function is a reusable piece of code that does a job. The job of `print()` is to show something on the screen. The thing inside the brackets is what it shows.

---

## Part 4: Running Python Code

There are three ways to run this file. Aman should know all three.

### Way 1: The terminal

Open the VS Code terminal (**View → Terminal**, or `` Ctrl + ` ``). Type:

```bash
python hello.py
```

On Mac/Linux you may need `python3 hello.py`.

Output:

```plaintext
Hello, world!
```

### Way 2: The Run button

In the top-right corner of VS Code there is a **▶ Run** button. Click it. VS Code runs the file in the terminal for you.

### Way 3: Interactive (line by line)

Select a line of code and press **Shift + Enter**. VS Code sends that line to an interactive Python window. This is useful when you want to test small pieces without running the whole file.

### Which one should I use?

| Way | Use when |
| --- | --- |
| Terminal | You want to understand what really happens |
| Run button | You want speed |
| Shift + Enter | You want to test one line at a time |

Neha says: "Use the terminal at first. When you type `python hello.py` yourself, you learn that Python is just a program that reads your file. That is the real mental model."

### Practice

1. Create a folder, open it in VS Code, and make a file `hello.py` that prints your name.
2. Run it in three ways: terminal, Run button, and Shift + Enter.
3. Why should the file name end with `.py`?

---

## Part 5: Understanding Python Environments

Aman's program works. Now Neha introduces the idea that confuses most beginners: **environments**.

### The problem

Imagine Aman works on two projects:

- Project A needs an old version of a library, say `pandas 1.5`.
- Project B needs the new version, `pandas 2.2`.

If both projects share **one** Python installation, they fight. Installing one breaks the other.

### The solution

Give each project its **own private Python environment**. Each environment has its own copy of installed packages. Project A gets its `pandas 1.5`. Project B gets its `pandas 2.2`. They never touch each other.

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/a8f6da1f-6b8d-4275-a93f-8dc10e922117.png align="center")

### What is a package? What is pip?

A **package** (or library) is code written by someone else that you can use in your project. For example:

- `requests` → talk to websites and APIs
- `pandas` → work with tables of data
- `openai` → talk to AI models

**pip** is Python's package installer. It downloads packages from the internet (from a site called PyPI, the Python Package Index) and installs them.

Think of pip like an app store for Python code.

---

## Part 6: Creating a Virtual Environment (venv)

A **virtual environment** is the private environment we just talked about. Python has a built-in tool for this called `venv`.

### Step 1: Create it

In the VS Code terminal, inside your project folder, run:

```bash
python -m venv .venv
```

Let's read this:

- `python -m venv` → run the `venv` module
- `.venv` → the name of the folder to create

A new folder called `.venv` appears in your project. It contains a fresh copy of Python with no extra packages. The dot at the start makes it a "hidden" folder on Mac/Linux, which keeps things tidy.

### Step 2: Activate it

Creating the environment is not enough. You must **activate** it so the terminal uses it.

Windows (PowerShell):

```bash
.venv\Scripts\activate
```

Mac/Linux:

```bash
source .venv/bin/activate
```

After this, your terminal prompt shows `(.venv)` at the start. That is the sign that the environment is active.

```plaintext
(.venv) C:\Users\Aman\projects\python-course>
```

### Deactivate

To leave the environment:

```bash
deactivate
```

### Practice

1. Create a virtual environment named `.venv` in your project.
2. Activate it. What do you see at the start of your terminal prompt?
3. Why do we need a separate environment for each project?

---

## Part 7: Installing Python Packages (pip install)

With the environment active, Aman installs his first package:

```bash
pip install requests
```

pip downloads `requests` and all the packages it depends on, and installs them *inside* `.venv`. Nothing is installed on the system Python.

### Check what is installed

```bash
pip list
```

This prints every package in the current environment with its version.

### Install a specific version

```bash
pip install requests==2.31.0
```

### Uninstall

```bash
pip uninstall requests
```

### Save your package list

Professionals keep a file called `requirements.txt` that lists all packages. Then anyone can install them with one command:

```bash
pip freeze > requirements.txt     # save the list
pip install -r requirements.txt   # install from the list
```

We will use this more in a future article.

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/a134180a-3868-4feb-b8c6-be336dd480ff.png align="center")

---

## Part 8: Using Python Packages (import)

Installing is step one. Using it is step two. To use a package in your code, you **import** it.

```python
import requests

response = requests.get("https://api.github.com")
print(response.status_code)
```

Output:

```plaintext
200
```

`200` means "OK, the request worked." In one line, Aman talked to GitHub's servers. That is the power of packages.

### Different ways to import

```python
import math                 # import the whole module
print(math.sqrt(16))        # 4.0

from math import sqrt       # import only one thing
print(sqrt(16))             # 4.0

import pandas as pd         # import with a short nickname
```

The `as pd` form is very common in data and AI work.

### Built-in vs installed

Some modules come with Python already. You do not need `pip install` for them. Examples: `math`, `os`, `random`, `json`, `datetime`. These are the **standard library**.

Packages like `requests`, `pandas`, and `openai` are **third-party**. You must install them first.

### Practice

1. Install `requests` and run the GitHub example above. What status code do you get?
2. What is the difference between `import math` and `from math import sqrt`?
3. Do you need to `pip install` the `random` module? Why or why not?

---

## Part 9: Comments

Before learning data types, one small but important tool: **comments**.

A comment is text in your code that Python **ignores**. It is for humans.

```python
# This line is a comment. Python skips it.
print("Hello")  # This is a comment at the end of a line
```

Everything after `#` on a line is a comment.

For longer notes, use triple quotes:

```python
"""
This is a multi-line text.
Python does not run it.
People often use it to describe a file or a function.
"""
```

### Good comments vs bad comments

Bad (just repeats the code):

```python
x = x + 1  # add 1 to x
```

Good (explains *why*):

```python
x = x + 1  # move to the next page of results
```

Neha's tip: "Write comments for your future self. In three months, you will not remember why you wrote that line."

Also, comments are a quick way to *disable* a line while testing. In VS Code, select lines and press `Ctrl + /` to comment or uncomment them.

---

## Part 10: Numbers (Integers and Floats)

Python has two main number types.

### Integers (int) — whole numbers

```python
age = 25
year = 2026
temperature = -5
```

### Floats — numbers with a decimal point

```python
price = 99.99
pi = 3.14159
half = 0.5
```

### Basic maths

```python
print(10 + 3)    # 13
print(10 - 3)    # 7
print(10 * 3)    # 30
print(10 / 3)    # 3.3333333333333335  (division always gives a float)
print(10 // 3)   # 3   (floor division: drop the decimal)
print(10 % 3)    # 1   (modulo: the remainder)
print(10 ** 3)   # 1000 (power)
```

Two surprises for beginners:

1. `/` always returns a float, even `10 / 2` gives `5.0`.
2. `//` and `%` are very useful. `%` tells you if a number is even: `n % 2 == 0`.

### Check the type

```python
print(type(25))      # <class 'int'>
print(type(25.0))    # <class 'float'>
```

### Convert between them

```python
int(3.9)      # 3  (cuts off the decimal, does NOT round)
float(7)      # 7.0
round(3.7)    # 4
```

### Practice

1. What does `7 / 2` give? And `7 // 2`? And `7 % 2`?
2. What is `type(10 / 2)`?
3. What does `int(9.99)` give?

---

## Part 11: Strings

A **string** is text. It goes inside quotes.

```python
name = "Aman"
drink = 'chai'
```

Single or double quotes both work. Pick one style and stay consistent. Use the other when you need a quote inside:

```python
sentence = "It's a nice day"
```

### Joining strings

```python
first = "Aman"
last = "Sharma"
full = first + " " + last
print(full)   # Aman Sharma
```

This is called **concatenation**.

### Length and indexing

```python
word = "python"
print(len(word))    # 6
print(word[0])      # p   (first character; counting starts at 0)
print(word[-1])     # n   (last character)
print(word[0:3])    # pyt (slice: from 0 up to, but not including, 3)
```

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/762b4941-a55b-453a-b55c-94de72d7e6ae.png align="center")

### Multi-line strings

```python
message = """Dear Aman,
Your order is ready.
Thank you!"""
```

### Mixing numbers and strings

This is a common error:

```python
age = 25
print("I am " + age)   # TypeError!
```

Python cannot join a string and a number. You must convert:

```python
print("I am " + str(age))   # works
```

But there is a better way, coming next.

---

## Part 12: String Formatting (f-strings)

An **f-string** lets you put variables inside a string easily. Put `f` before the opening quote and use `{}` for variables.

```python
name = "Aman"
age = 25
print(f"My name is {name} and I am {age} years old.")
```

Output:

```plaintext
My name is Aman and I am 25 years old.
```

No `str()`. No `+`. Just clean text.

You can even do maths inside:

```python
price = 50
qty = 3
print(f"Total: {price * qty} rupees")   # Total: 150 rupees
```

And control decimals:

```python
pi = 3.14159
print(f"Pi is about {pi:.2f}")   # Pi is about 3.14
```

Neha says: **"Use f-strings. Always. They are the modern way."**

### Practice

1. Write an f-string that prints: `Hello, <your name>! You are <age> years old.`
2. What is wrong with `print("Score: " + 95)`? Fix it in two ways.
3. Use an f-string to print `19.99` rounded to one decimal place.

---

## Part 13: String Methods

A **method** is a function that belongs to an object. You call it with a dot. Strings have many useful methods.

```python
text = "  Chai aur Code  "

print(text.upper())      # "  CHAI AUR CODE  "
print(text.lower())      # "  chai aur code  "
print(text.strip())      # "Chai aur Code"   (remove spaces at both ends)
print(text.title())      # "  Chai Aur Code  "
```

```python
email = "aman@example.com"

print(email.startswith("aman"))   # True
print(email.endswith(".com"))     # True
print(email.replace("aman", "neha"))   # neha@example.com
print(email.split("@"))           # ['aman', 'example.com']
```

```python
sentence = "python is fun"
print(sentence.count("n"))   # 2
print(sentence.find("is"))   # 7  (index where "is" starts)
print("fun" in sentence)     # True
```

### Important: strings are immutable

Remember from the last article: strings **cannot** be changed. So `text.upper()` does **not** change `text`. It returns a **new** string.

```python
name = "aman"
name.upper()
print(name)          # aman   (unchanged!)

name = name.upper()  # save the result
print(name)          # AMAN
```

This mistake is extremely common. Always save the result.

### Discover methods yourself

In VS Code, type `text.` and wait. A list of all methods appears. Or in the Python shell, type `dir("")`.

### Practice

1. Take the string `" Hello World "`. Remove the spaces and make it all lowercase.
2. Split `"a,b,c,d"` into a list using `split()`.
3. Why does this print `hello` and not `HELLO`?

   ```python
   s = "hello"
   s.upper()
   print(s)
   ```

---

## Part 14: Booleans

A **boolean** has only two values: `True` or `False`. (Note the capital first letter.)

```python
is_logged_in = True
has_paid = False
```

Booleans usually come from comparisons:

```python
age = 25
print(age > 18)     # True
print(age == 30)    # False
```

### Truthy and falsy

Python can treat other values as `True` or `False`:

| Value | Treated as |
| --- | --- |
| `0`, `0.0` | False |
| `""` (empty string) | False |
| `[]`, `{}`, `()` (empty collections) | False |
| `None` | False |
| Everything else | True |

```python
print(bool(0))        # False
print(bool(42))       # True
print(bool(""))       # False
print(bool("chai"))   # True
```

This is useful for checks like `if name:` which means "if name is not empty".

---

## Part 15: Operators

An **operator** is a symbol that does something with values. Python has three main groups.

### Arithmetic (maths)

| Operator | Meaning | Example | Result |
| --- | --- | --- | --- |
| `+` | add | `5 + 2` | `7` |
| `-` | subtract | `5 - 2` | `3` |
| `*` | multiply | `5 * 2` | `10` |
| `/` | divide | `5 / 2` | `2.5` |
| `//` | floor divide | `5 // 2` | `2` |
| `%` | remainder | `5 % 2` | `1` |
| `**` | power | `5 ** 2` | `25` |

### Membership (in / not in)

beginners often miss: **membership operators**. They check if a value is **inside** a collection.

| Operator | Meaning | Example | Result |
| --- | --- | --- | --- |
| `in` | is it inside? | `"a" in "chai"` | `True` |
| `not in` | is it NOT inside? | `"x" in "chai"` | `False` |

They work with strings, lists, tuples, sets, and dictionaries.

**In a string** (checks for a substring):

```python
sentence = "python is fun"
print("fun" in sentence)      # True
print("java" in sentence)     # False
```

**In a list**:

```python
drinks = ["chai", "coffee", "lassi"]
print("chai" in drinks)       # True
print("juice" not in drinks)  # True
```

**In a dictionary** (checks the **keys**, not the values):

```python
person = {"name": "Aman", "age": 25}
print("name" in person)    # True
print("Aman" in person)    # False  ← "Aman" is a value, not a key
```

**In an** `if`:

```python
email = "aman@example.com"

if "@" in email:
    print("Looks like an email")
else:
    print("Missing @")
```

Membership operators always return a boolean, so you can combine them with `and`, `or`, and `not`:

```python
is_valid = "@" in email and "." in email
```

### Comparison (gives True/False)

| Operator | Meaning | Example | Result |
| --- | --- | --- | --- |
| `==` | equal | `5 == 5` | `True` |
| `!=` | not equal | `5 != 3` | `True` |
| `>` | greater | `5 > 3` | `True` |
| `<` | less | `5 < 3` | `False` |
| `>=` | greater or equal | `5 >= 5` | `True` |
| `<=` | less or equal | `5 <= 4` | `False` |

Careful: `=` assigns a value. `==` compares. Mixing them is a classic beginner bug.

### Logical (combine True/False)

| Operator | Meaning | Example | Result |
| --- | --- | --- | --- |
| `and` | both must be True | `True and False` | `False` |
| `or` | at least one True | `True or False` | `True` |
| `not` | flip it | `not True` | `False` |

```python
age = 25
has_ticket = True

can_enter = age >= 18 and has_ticket
print(can_enter)    # True
```

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/a9adef59-abb9-4c0f-9c86-dbb40cce363b.png align="center")

---

## Part 16: Shortcut Assignments (+=)

This is very common:

```python
count = 0
count = count + 1
```

Python has a shortcut:

```python
count += 1    # same as count = count + 1
```

It works for other operators too:

```python
total -= 5     # total = total - 5
price *= 2     # price = price * 2
score /= 4     # score = score / 4
```

And for strings:

```python
msg = "Hello"
msg += " World"
print(msg)     # Hello World
```

### Practice

1. What does `7 % 3` give? What does `2 ** 4` give?
2. What is the result of `not (5 > 3)`?
3. What is `x` after this?

   ```python
   x = 10
   x += 5
   x *= 2
   ```
4. Is `age = 18` the same as `age == 18`? Explain.

---

## Part 17: Control Flow — Conditional Statements

So far, Aman's programs run line by line from top to bottom. **Control flow** lets the program make decisions and repeat things.

### if

```python
temperature = 35

if temperature > 30:
    print("It is hot. Make cold coffee.")
```

Three rules:

1. The condition comes after `if`.
2. A colon `:` ends the line.
3. The code inside is **indented** (4 spaces). Indentation is not optional in Python. It is how Python knows what belongs to the `if`.

### if / else

```python
if temperature > 30:
    print("Cold coffee")
else:
    print("Hot chai")
```

### if / elif / else

`elif` means "else if". Use it for more than two choices.

```python
marks = 72

if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 60:
    print("Grade C")
else:
    print("Try again")
```

Output: `Grade C`

Python checks each condition from the top. The **first** one that is `True` runs. The rest are skipped. If none is `True`, `else` runs.

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/46f922d3-fdf0-4cee-8ebd-aa47b5e11ca1.png align="center")

### Combining conditions

```python
age = 20
is_member = True

if age >= 18 and is_member:
    print("Welcome!")
```

### Practice

1. Write a program that checks if a number is even or odd. (Hint: use `%`.)
2. What will this print?

   ```python
   x = 50
   if x > 100:
       print("Big")
   elif x > 10:
       print("Medium")
   else:
       print("Small")
   ```
3. What happens if you forget the indentation inside an `if`?

---

## Part 18: Loops (for loops and range())

A **loop** repeats code. The most common loop in Python is the `for` loop.

### Looping over a list

```python
drinks = ["chai", "coffee", "lassi"]

for drink in drinks:
    print(drink)
```

Output:

```plaintext
chai
coffee
lassi
```

Read it as: "For each `drink` in `drinks`, do this."

`drink` is a variable that Python creates for you. Each time through the loop, it holds the next item.

### Looping over a string

```python
for letter in "abc":
    print(letter)
```

### Looping a fixed number of times: range()

`range()` makes a sequence of numbers.

```python
for i in range(5):
    print(i)
```

Output:

```plaintext
0
1
2
3
4
```

Note: `range(5)` gives 0 to 4. It **starts at 0** and **stops before 5**.

Other forms:

```python
range(1, 6)       # 1, 2, 3, 4, 5
range(0, 10, 2)   # 0, 2, 4, 6, 8   (step of 2)
```

### Loop with a counter

```python
total = 0
for n in range(1, 11):
    total += n
print(total)   # 55
```

### break and continue

```python
for n in range(10):
    if n == 3:
        continue   # skip this one, go to next
    if n == 6:
        break      # stop the loop completely
    print(n)
```

Output: `0 1 2 4 5`

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/53f2ed66-9065-4d23-a6c1-864b195a6e7e.png align="center")

### Practice

1. Print numbers from 1 to 10 using `range()`.
2. Print all even numbers between 0 and 20.
3. What does this print?

   ```python
   for i in range(2, 8, 3):
       print(i)
   ```
4. Add up all numbers from 1 to 100 using a loop.

---

## Part 19: Data Structures — Introduction

A **data structure** is a way to store many values together. Python has four built-in ones that you will use every day:

| Structure | Symbol | Ordered? | Can change? | Duplicates? |
| --- | --- | --- | --- | --- |
| List | `[ ]` | Yes | Yes | Yes |
| Dictionary | `{key: value}` | Yes (by insertion) | Yes | Keys no |
| Tuple | `( )` | Yes | No | Yes |
| Set | `{ }` | No | Yes | No |

Let's look at each one.

---

## Part 20: Lists

A **list** is an ordered collection. You can add, remove, and change items.

```python
drinks = ["chai", "coffee", "lassi"]
```

### Access items

```python
print(drinks[0])     # chai
print(drinks[-1])    # lassi
print(drinks[0:2])   # ['chai', 'coffee']
print(len(drinks))   # 3
```

### Change items

```python
drinks[1] = "tea"
print(drinks)   # ['chai', 'tea', 'lassi']
```

### Add items

```python
drinks.append("juice")          # add to the end
drinks.insert(0, "water")       # add at position 0
```

### Remove items

```python
drinks.remove("lassi")   # remove by value
drinks.pop()             # remove and return the last item
drinks.pop(0)            # remove and return item at index 0
```

### Other useful things

```python
numbers = [5, 2, 9, 1]
numbers.sort()           # [1, 2, 5, 9]
print(max(numbers))      # 9
print(min(numbers))      # 1
print(sum(numbers))      # 17
print(9 in numbers)      # True
```

### Lists can hold anything

```python
mixed = [1, "two", 3.0, True, [4, 5]]
```

Even other lists.

### Loop over a list with index

```python
for i, drink in enumerate(drinks):
    print(i, drink)
```

---

## Part 21: Dictionaries

A **dictionary** stores **key → value** pairs. Think of a real dictionary: word → meaning.

```python
person = {
    "name": "Aman",
    "age": 25,
    "city": "Ahmedabad"
}
```

### Access by key

```python
print(person["name"])    # Aman
print(person.get("age")) # 25
```

`person["email"]` would crash because the key does not exist. `person.get("email")` returns `None` instead. Use `.get()` when you are not sure the key exists.

### Add or change

```python
person["email"] = "aman@example.com"   # add
person["age"] = 26                      # change
```

### Remove

```python
del person["city"]
```

### Loop

```python
for key, value in person.items():
    print(f"{key}: {value}")
```

### Useful methods

```python
person.keys()     # all keys
person.values()   # all values
"name" in person  # True
```

Dictionaries are everywhere in AI work. API responses, JSON data, and model settings are almost always dictionaries.

![](https://cdn.hashnode.com/uploads/covers/68822b6ad516e7a593530cf9/671d0f1f-0aeb-4c57-b0d0-1b9b5b438326.png align="center")

---

## Part 22: Tuples

A **tuple** is like a list, but **immutable**. Once created, it cannot change.

```python
point = (3, 4)
colors = ("red", "green", "blue")
```

### Access

```python
print(point[0])    # 3
print(len(colors)) # 3
```

### Cannot change

```python
point[0] = 10   # TypeError!
```

### Why use a tuple?

- When the data should **not** change (coordinates, RGB colors, days of the week).
- They are slightly faster and use less memory than lists.
- They can be used as dictionary keys. Lists cannot.

### Unpacking

```python
x, y = point
print(x)   # 3
print(y)   # 4
```

This is very common with functions that return multiple values.

---

## Part 23: Sets

A **set** is a collection with **no duplicates** and **no order**.

```python
tags = {"python", "ai", "python", "code"}
print(tags)   # {'python', 'ai', 'code'}  — duplicate removed
```

### Remove duplicates from a list

The number-one use of a set:

```python
numbers = [1, 2, 2, 3, 3, 3]
unique = set(numbers)
print(unique)         # {1, 2, 3}
print(list(unique))   # back to a list
```

### Add and remove

```python
tags.add("ml")
tags.remove("code")
```

### Set maths

```python
a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)   # union: {1, 2, 3, 4, 5}
print(a & b)   # intersection: {3}
print(a - b)   # difference: {1, 2}
```

### Careful: empty set

`{}` is an empty **dictionary**, not an empty set. For an empty set, write `set()`.

### Practice (Data Structures)

1. Make a list of 5 numbers. Print the largest, the smallest, and the sum.
2. Make a dictionary with keys `title`, `author`, `year` for your favourite book. Print each key and value using a loop.
3. Why would you use a tuple instead of a list for `(latitude, longitude)`?
4. Remove duplicates from `[“a”, “b”, “a”, “c”, “b”]` and print the result.
5. What is the difference between `person["email"]` and `person.get("email")` when the key does not exist?

---

## Part 24: Final Quiz

Try these without looking back. Answers are at the end.

**Q1.** What command creates a virtual environment called `.venv`?

**Q2.** After activating a virtual environment, what appears at the start of your terminal prompt?

**Q3.** What does `pip install requests` do, and where does it install the package?

**Q4.** Which of these needs `pip install` before use: `math`, `requests`, `random`, `pandas`?

**Q5.** What does this print?

```python
name = "Neha"
print(f"Hi {name.upper()}, you have {3 * 4} messages")
```

**Q6.** What does `10 // 3` give? What does `10 % 3` give?

**Q7.** What does this print?

```python
for i in range(1, 10, 3):
    print(i)
```

**Q8.** What is the output?

```python
x = 7
if x % 2 == 0:
    print("even")
else:
    print("odd")
```

**Q9.** Which data structure would you use for each?

- A shopping cart where items can be added and removed
- A fixed pair of (width, height)
- Storing a user's name, email, and age
- A list of unique visitor IDs

**Q10.** What is wrong here?

```python
s = "hello"
s.upper()
print(s)   # expected HELLO
```

---

### Answers

**Part 4:**

1. Your own file.
2. Done in your editor.
3. The `.py` extension tells Python and VS Code that the file contains Python code.

**Part 6:**

1. `python -m venv .venv`
2. `(.venv)`
3. So each project has its own packages and versions, and projects do not break each other.

**Part 8:**

1. `200`
2. `import math` brings the whole module (use `math.sqrt`); `from math import sqrt` brings only `sqrt` (use `sqrt` directly).
3. No. `random` is part of the standard library and comes with Python.

**Part 10:**

1. `3.5`, `3`, `1`
2. `<class 'float'>` (division always gives a float)
3. `9`

**Part 12:**

1. Example: `print(f"Hello, {name}! You are {age} years old.")`
2. You cannot add a string and an int. Fix: `print("Score: " + str(95))` or `print(f"Score: {95}")`.
3. `print(f"{19.99:.1f}")` → `20.0`

**Part 13:**

1. `" Hello World ".strip().lower()` → `hello world`
2. `"a,b,c,d".split(",")` → `['a', 'b', 'c', 'd']`
3. Strings are immutable. `s.upper()` returns a new string, but it was not saved. `s` is unchanged.

**Part 16:**

1. `1`, `16`
2. `False`
3. `30`
4. No. `=` assigns 18 to `age`. `==` checks if `age` equals 18 and gives `True`/`False`.

**Part 17:** 1.

```python
n = 7
if n % 2 == 0:
    print("even")
else:
    print("odd")
```

2. `Medium`
3. Python gives an `IndentationError`.

**Part 18:**

1. `for i in range(1, 11): print(i)`
2. `for i in range(0, 21, 2): print(i)`
3. `2`, `5`

```python
total = 0
for n in range(1, 101):
    total += n
print(total)   # 5050
```

**Part 23 (Data Structures):**

1. Use `max()`, `min()`, `sum()`.
2. Use `for key, value in book.items(): print(f"{key}: {value}")`
3. Because the coordinates should not change by accident, and a tuple makes that clear.
4. `list(set(["a", "b", "a", "c", "b"]))` → `['a', 'b', 'c']` (order may vary)
5. `person["email"]` crashes with `KeyError`. `person.get("email")` returns `None`.

**Final Quiz:**

1. `python -m venv .venv`
2. `(.venv)`
3. Downloads `requests` from PyPI and installs it inside the active virtual environment (`.venv`).
4. `requests` and `pandas`. (`math` and `random` are built-in.)
5. `Hi NEHA, you have 12 messages`
6. `3` and `1`
7. `1`, `4`, `7`
8. `odd`
9. List; tuple; dictionary; set.
10. `s.upper()` returns a new string but it is not saved. Fix: `s = s.upper()`.

---

## Epilogue

Aman closes his laptop. In one session he went from a random file on the desktop to a proper project: a folder, a workspace, a virtual environment, an installed package, and working code that talks to the internet.

More importantly, he now has the basic tools of every program: numbers, strings, booleans, conditions, loops, and the four data structures.

Neha says, "Everything you build from now on — a chatbot, a data pipeline, an AI agent — is made from exactly these pieces. You just combine them in smarter ways."
