# Day 3 Python Notes

## Topics Covered

```text
1. List Slicing
2. Tuple
3. Dictionary
4. Set
5. Exception Handling
6. Different Types of Exceptions
7. File Handling
8. Login System Using File Handling and Exception Handling
```

* * *

# 1\. List Slicing

In Day 2, we learned about lists.

A list is used to store multiple values in one variable.

Example:

```python
fruits = ["apple", "banana", "mango", "orange", "grapes"]
```

Now, we will learn **list slicing**.

List slicing means taking a specific part of a list.

* * *

## List Index Revision

In Python, list index starts from `0`.

Example:

```python
fruits = ["apple", "banana", "mango", "orange"]
```

Index values:

```text
apple   -> index 0
banana  -> index 1
mango   -> index 2
orange  -> index 3
```

Example:

```python
fruits = ["apple", "banana", "mango", "orange"]

print(fruits[0])
print(fruits[1])
```

Output:

```python
apple
banana
```

* * *

## Basic List Slicing

Example:

```python
numbers = [10, 20, 30, 40, 50]

print(numbers[0:3])
```

Output:

```python
[10, 20, 30]
```

Explanation:

```python
numbers[0:3]
```

means start from index `0` and stop before index `3`.

It includes:

```python
numbers[0]
numbers[1]
numbers[2]
```

It does not include index `3`.

* * *

## More List Slicing Examples

```python
numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:3])
print(numbers[2:5])
print(numbers[:4])
print(numbers[3:])
```

Output:

```python
[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
[40, 50, 60]
```

Explanation:

```python
numbers[0:3]
```

starts from index `0` and stops before index `3`.

```python
numbers[2:5]
```

starts from index `2` and stops before index `5`.

```python
numbers[:4]
```

starts from the beginning and stops before index `4`.

```python
numbers[3:]
```

starts from index `3` and goes until the end.

* * *

## Negative Indexing

Python also supports negative indexing.

Example:

```python
fruits = ["apple", "banana", "mango", "orange"]

print(fruits[-1])
print(fruits[-2])
```

Output:

```python
orange
mango
```

Explanation:

```python
-1
```

means last item.

```python
-2
```

means second last item.

* * *

## Negative Slicing

Example:

```python
numbers = [10, 20, 30, 40, 50, 60]

print(numbers[-3:])
```

Output:

```python
[40, 50, 60]
```

Explanation:

```python
numbers[-3:]
```

means take the last three items.

* * *

## Slicing With Step

Example:

```python
numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:6:2])
```

Output:

```python
[10, 30, 50]
```

Explanation:

```python
numbers[0:6:2]
```

means:

```text
Start from index 0
Stop before index 6
Move by step 2
```

* * *

## Reverse a List Using Slicing

Example:

```python
numbers = [10, 20, 30, 40, 50]

print(numbers[::-1])
```

Output:

```python
[50, 40, 30, 20, 10]
```

Explanation:

```python
[::-1]
```

is used to reverse a list.

* * *

## List Slicing Questions

### Question 1

Print the first three items from a list.

Solution:

```python
fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[0:3])
```

Output:

```python
['apple', 'banana', 'mango']
```

* * *

### Question 2

Print the last two items from a list.

Solution:

```python
fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[-2:])
```

Output:

```python
['orange', 'grapes']
```

* * *

### Question 3

Reverse a list using slicing.

Solution:

```python
numbers = [1, 2, 3, 4, 5]

print(numbers[::-1])
```

Output:

```python
[5, 4, 3, 2, 1]
```

* * *

# 2\. Tuple

A tuple is used to store multiple values in one variable.

It is similar to a list.

But the main difference is:

```text
List is changeable.
Tuple is not changeable.
```

That means after creating a tuple, we cannot directly add, remove, or change its items.

Example:

```python
fruits = ("apple", "banana", "mango")

print(fruits)
```

Output:

```python
('apple', 'banana', 'mango')
```

Here, `fruits` is a tuple.

* * *

## Accessing Tuple Items

Tuple index also starts from `0`, just like list.

Example:

```python
fruits = ("apple", "banana", "mango")

print(fruits[0])
print(fruits[1])
print(fruits[2])
```

Output:

```python
apple
banana
mango
```

Explanation:

```python
fruits[0]
```

gives `"apple"`.

```python
fruits[1]
```

gives `"banana"`.

```python
fruits[2]
```

gives `"mango"`.

* * *

## Tuple Cannot Be Changed

Example:

```python
fruits = ("apple", "banana", "mango")

fruits[0] = "orange"

print(fruits)
```

This gives an error.

Because tuple does not allow item change.

* * *

## Why Use Tuple?

We use tuple when we want to store values that should not change.

Example:

```python
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
```

Days of the week are fixed, so tuple is a good choice.

Another example:

```python
location = (26.4525, 87.2718)
```

This can store latitude and longitude.

* * *

## Looping Through Tuple

Example:

```python
fruits = ("apple", "banana", "mango")

for fruit in fruits:
    print(fruit)
```

Output:

```python
apple
banana
mango
```

Explanation:

Tuple is iterable.

So we can use a `for` loop to read each item one by one.

* * *

## Tuple Question 1

Write a program to store five student names in a tuple and print them one by one.

Solution:

```python
students = ("Ram", "Sita", "Hari", "Gita", "Shyam")

for student in students:
    print(student)
```

Output:

```python
Ram
Sita
Hari
Gita
Shyam
```

* * *

## Tuple Question 2

Write a program to find the length of a tuple.

Solution:

```python
numbers = (10, 20, 30, 40, 50)

print("Total items:", len(numbers))
```

Output:

```python
Total items: 5
```

Explanation:

`len()` counts how many items are inside the tuple.

* * *

## Tuple Question 3

Write a program to check whether `"apple"` exists in a tuple or not.

Solution:

```python
fruits = ("apple", "banana", "mango")

if "apple" in fruits:
    print("Apple exists")
else:
    print("Apple does not exist")
```

Output:

```python
Apple exists
```

* * *

# 3\. Dictionary

A dictionary is used to store data in **key-value pairs**.

Example:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student)
```

Output:

```python
{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
```

Here:

```python
"name"
```

is a key.

```python
"Ram"
```

is the value.

* * *

## Real-Life Example of Dictionary

A student has different details:

```text
Name: Ram
Age: 18
Address: Kathmandu
```

In Python, we can store this like:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}
```

Dictionary is useful when we want to store related information.

* * *

## Accessing Dictionary Values

Example:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student["name"])
print(student["age"])
print(student["address"])
```

Output:

```python
Ram
18
Kathmandu
```

Explanation:

We use the key to access the value.

```python
student["name"]
```

gives `"Ram"`.

* * *

## Updating Dictionary Value

Example:

```python
student = {
    "name": "Ram",
    "age": 18
}

student["age"] = 19

print(student)
```

Output:

```python
{'name': 'Ram', 'age': 19}
```

Explanation:

The value of `"age"` was changed from `18` to `19`.

* * *

## Adding New Key-Value Pair

Example:

```python
student = {
    "name": "Ram",
    "age": 18
}

student["address"] = "Kathmandu"

print(student)
```

Output:

```python
{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
```

Explanation:

A new key `"address"` was added to the dictionary.

* * *

## Removing Item from Dictionary

Example:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

student.pop("age")

print(student)
```

Output:

```python
{'name': 'Ram', 'address': 'Kathmandu'}
```

Explanation:

`pop()` removes the item with the given key.

* * *

## Looping Through Dictionary

Example:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(key)
```

Output:

```python
name
age
address
```

This prints only keys.

To print values:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(student[key])
```

Output:

```python
Ram
18
Kathmandu
```

To print both key and value:

```python
student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key, value in student.items():
    print(key, ":", value)
```

Output:

```python
name : Ram
age : 18
address : Kathmandu
```

* * *

## Dictionary Question 1

Write a program to store student name, age, and address in a dictionary and print them.

Solution:

```python
student = {
    "name": "Sita",
    "age": 19,
    "address": "Pokhara"
}

print("Name:", student["name"])
print("Age:", student["age"])
print("Address:", student["address"])
```

Output:

```python
Name: Sita
Age: 19
Address: Pokhara
```

* * *

## Dictionary Question 2

Write a program to store product name, price, and quantity. Then calculate total price.

Solution:

```python
product = {
    "name": "Pen",
    "price": 20,
    "quantity": 5
}

total = product["price"] * product["quantity"]

print("Product:", product["name"])
print("Total price:", total)
```

Output:

```python
Product: Pen
Total price: 100
```

Explanation:

Price is `20`.

Quantity is `5`.

So:

```python
20 * 5 = 100
```

* * *

## Dictionary Question 3

Write a program to update a student's marks.

Solution:

```python
student = {
    "name": "Ram",
    "marks": 75
}

student["marks"] = 85

print(student)
```

Output:

```python
{'name': 'Ram', 'marks': 85}
```

* * *

# 4\. Set

A set is used to store multiple values in one variable.

But set has two important features:

```text
1. Set does not allow duplicate values.
2. Set does not maintain fixed order.
```

Example:

```python
numbers = {10, 20, 30, 40}

print(numbers)
```

Output may be:

```python
{40, 10, 20, 30}
```

The order may be different.

That is normal in set.

* * *

## Set Does Not Allow Duplicate Values

Example:

```python
numbers = {10, 20, 20, 30, 30, 40}

print(numbers)
```

Output:

```python
{40, 10, 20, 30}
```

Explanation:

Duplicate values are automatically removed.

* * *

## Adding Item to Set

Example:

```python
fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)
```

Output may be:

```python
{'apple', 'banana', 'mango'}
```

The order may be different.

* * *

## Removing Item from Set

Example:

```python
fruits = {"apple", "banana", "mango"}

fruits.remove("banana")

print(fruits)
```

Output:

```python
{'apple', 'mango'}
```

* * *

## Looping Through Set

Example:

```python
fruits = {"apple", "banana", "mango"}

for fruit in fruits:
    print(fruit)
```

Output may be:

```python
banana
apple
mango
```

Explanation:

Set is iterable.

But the order is not fixed.

* * *

## Why Use Set?

Set is useful when we want unique values only.

Example:

```python
students = {"Ram", "Sita", "Ram", "Hari", "Sita"}

print(students)
```

Output:

```python
{'Ram', 'Sita', 'Hari'}
```

Duplicate names are removed.

* * *

## Set Question 1

Write a program to remove duplicate numbers from a list.

Solution:

```python
numbers = [10, 20, 20, 30, 30, 40]

unique_numbers = set(numbers)

print(unique_numbers)
```

Output:

```python
{40, 10, 20, 30}
```

Explanation:

The list contains duplicate values.

When we convert it into a set, duplicate values are removed.

* * *

## Set Question 2

Write a program to add a new student name in a set.

Solution:

```python
students = {"Ram", "Sita", "Hari"}

students.add("Gita")

print(students)
```

Output may be:

```python
{'Ram', 'Sita', 'Hari', 'Gita'}
```

* * *

## Set Question 3

Write a program to check whether `"Ram"` exists in a set or not.

Solution:

```python
students = {"Ram", "Sita", "Hari"}

if "Ram" in students:
    print("Ram exists")
else:
    print("Ram does not exist")
```

Output:

```python
Ram exists
```

* * *

# 5\. Exception Handling

Exception handling means handling errors in a program.

Sometimes our program may get an error while running.

Example:

```python
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a / b)
```

If the user enters:

```python
10
0
```

Then the program gives an error because division by zero is not allowed.

To handle this kind of error, we use:

```python
try
except
```

* * *

## Basic Try Except

Example:

```python
try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except:
    print("Something went wrong")
```

Explanation:

The code that may cause an error is written inside `try`.

If an error happens, the code inside `except` runs.

So instead of crashing, the program shows a message.

* * *

## Better Try Except

It is better to mention the exact error name.

Example:

```python
try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ZeroDivisionError:
    print("Cannot divide by zero")

except ValueError:
    print("Please enter numbers only")
```

Explanation:

`ZeroDivisionError` happens when we divide by zero.

`ValueError` happens when we enter invalid number input.

* * *

# 6\. Different Types of Exceptions

Python has many types of exceptions.

Some common exceptions are:

```text
1. ValueError
2. ZeroDivisionError
3. FileNotFoundError
4. IndexError
5. KeyError
6. TypeError
7. NameError
8. PermissionError
```

* * *

## 1\. ValueError

`ValueError` happens when the value is not valid.

Example:

```python
age = int("hello")
```

This gives an error because `"hello"` cannot be converted into an integer.

Correct handling:

```python
try:
    age = int(input("Enter your age: "))
    print("Your age is", age)

except ValueError:
    print("Please enter a valid number")
```

* * *

## 2\. ZeroDivisionError

`ZeroDivisionError` happens when we divide a number by zero.

Example:

```python
try:
    a = 10
    b = 0

    result = a / b

    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero")
```

Output:

```python
Cannot divide by zero
```

* * *

## 3\. FileNotFoundError

`FileNotFoundError` happens when we try to read a file that does not exist.

Example:

```python
try:
    with open("data.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File not found")
```

* * *

## 4\. IndexError

`IndexError` happens when we try to access an index that does not exist in a list.

Example:

```python
try:
    numbers = [10, 20, 30]

    print(numbers[5])

except IndexError:
    print("Index does not exist")
```

Output:

```python
Index does not exist
```

Explanation:

The list has only three items.

Available indexes are:

```python
0, 1, 2
```

But we tried to access index `5`.

So `IndexError` happened.

* * *

## 5\. KeyError

`KeyError` happens when we try to access a dictionary key that does not exist.

Example:

```python
try:
    student = {
        "name": "Ram",
        "age": 18
    }

    print(student["address"])

except KeyError:
    print("Key does not exist")
```

Output:

```python
Key does not exist
```

Explanation:

The dictionary has only:

```python
name
age
```

But we tried to access:

```python
address
```

So `KeyError` happened.

* * *

## 6\. TypeError

`TypeError` happens when we perform an operation with the wrong data type.

Example:

```python
try:
    result = "Age: " + 20
    print(result)

except TypeError:
    print("Cannot add string and number directly")
```

Output:

```python
Cannot add string and number directly
```

Correct way:

```python
result = "Age: " + str(20)
print(result)
```

* * *

## 7\. NameError

`NameError` happens when we use a variable that has not been created.

Example:

```python
try:
    print(username)

except NameError:
    print("Variable is not defined")
```

Output:

```python
Variable is not defined
```

* * *

## 8\. PermissionError

`PermissionError` happens when Python does not have permission to read or write a file.

Example:

```python
try:
    with open("/root/data.txt", "w") as file:
        file.write("Hello")

except PermissionError:
    print("You do not have permission to write this file")
```

* * *

## Handling Multiple Exceptions Together

Example:

```python
try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ValueError:
    print("Please enter numbers only")

except ZeroDivisionError:
    print("Cannot divide by zero")

except Exception as e:
    print("Something went wrong:", e)
```

Explanation:

`ValueError` handles invalid input.

`ZeroDivisionError` handles division by zero.

`Exception` handles any other unexpected error.

* * *

## Try Except Else

`else` runs only when there is no error.

Example:

```python
try:
    age = int(input("Enter your age: "))

except ValueError:
    print("Please enter a valid number")

else:
    print("Your age is", age)
```

Explanation:

If the user enters a correct number, `else` runs.

If the user enters text like `"abc"`, `except` runs.

* * *

## Try Except Finally

`finally` always runs.

Example:

```python
try:
    number = int(input("Enter a number: "))
    print(number)

except ValueError:
    print("Invalid input")

finally:
    print("Program finished")
```

Explanation:

Whether error happens or not, `finally` runs.

* * *

# 7\. File Handling

File handling means working with files using Python.

Using file handling, we can:

```text
1. Create a file
2. Write data into a file
3. Read data from a file
4. Add new data into an existing file
```

* * *

## Opening a File

Python uses `open()` to open a file.

Syntax:

```python
file = open("filename.txt", "mode")
```

Common file modes:

```text
"r"  read mode
"w"  write mode
"a"  append mode
```

* * *

## Write Mode

Write mode is used to write data into a file.

Example:

```python
file = open("student.txt", "w")

file.write("Hello, this is my first file.")

file.close()
```

Explanation:

`student.txt` is the file name.

`"w"` means write mode.

`write()` writes data into the file.

`close()` closes the file.

Important:

If the file does not exist, Python creates it.

If the file already exists, write mode replaces old content.

* * *

## Reading a File

Example:

```python
file = open("student.txt", "r")

data = file.read()

print(data)

file.close()
```

Output:

```python
Hello, this is my first file.
```

Explanation:

`"r"` means read mode.

`read()` reads the file content.

* * *

## Append Mode

Append mode is used to add new data without deleting old data.

Example:

```python
file = open("student.txt", "a")

file.write("\nThis is new line.")

file.close()
```

Explanation:

`"a"` means append mode.

It adds new content at the end of the file.

`\n` means new line.

* * *

## Better Way: Using with open()

The better way to work with files is:

```python
with open("student.txt", "w") as file:
    file.write("Hello Python")
```

Here, we do not need to write:

```python
file.close()
```

Python automatically closes the file.

* * *

## Read File Using with open()

Example:

```python
with open("student.txt", "r") as file:
    data = file.read()
    print(data)
```

* * *

## File Handling With Exception Handling

File handling and exception handling are often used together.

Why?

Because file errors can happen.

For example:

```text
1. File may not exist.
2. User may enter wrong input.
3. Program may not have permission to read/write file.
```

Example:

```python
try:
    with open("student.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File does not exist")
```

Explanation:

If `student.txt` exists, Python reads the file.

If it does not exist, `FileNotFoundError` happens.

Then `except` block runs.

* * *

# 8\. File-Based Login System

Now we will create a simple login system using file handling.

In this system:

```text
Each user will have their own file.
The username will be used as the file name.
The password will be saved inside that file.
```

Example:

If username is:

```python
ram
```

Then Python creates:

```python
ram.txt
```

Inside `ram.txt`, the password is saved.

* * *

## Full Login System Code

```python
def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except FileNotFoundError:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")

    except Exception as e:
        print("Something went wrong while registering:", e)


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except FileNotFoundError:
        print("User not found")
        return

    except Exception as e:
        print("Something went wrong while opening user file:", e)
        return

    try:
        with open(f"{username}.txt", "r") as f:
            checkpass = f.readline()

            if password == checkpass:
                print("Welcome")
            else:
                print("Sorry, incorrect password")

    except Exception as e:
        print("Something went wrong while checking password:", e)


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()

    elif x == "l":
        login()

    else:
        print("Invalid choice")


ask()
```

* * *

# 9\. Explanation of Login System

## Register Function

```python
def register():
```

This function is used to register a new user.

```python
username = input("Enter your username: ")
password = input("Enter your password: ")
```

Here, the program asks the user to enter username and password.

* * *

## Checking If Username Already Exists

```python
try:
    file = open(f"{username}.txt", "r")
    print("Username already exists")
    file.close()
```

Here, the program tries to open a file with the username.

Example:

If username is:

```python
ram
```

Then it tries to open:

```python
ram.txt
```

If the file exists, it means the username is already registered.

So the program prints:

```python
Username already exists
```

* * *

## Creating File for New User

```python
except FileNotFoundError:
    with open(f"{username}.txt", "w") as f:
        f.write(password)

    print("User registered successfully")
```

If the file does not exist, Python gives `FileNotFoundError`.

That means the username is new.

So the program creates a new file and saves the password inside it.

Example:

If username is:

```python
sita
```

Then file name becomes:

```python
sita.txt
```

And inside that file, the password is saved.

* * *

## Login Function

```python
def login():
```

This function is used to login an existing user.

```python
username = input("Enter your username: ")
password = input("Enter your password: ")
```

The program asks for username and password.

* * *

## Checking If User Exists

```python
try:
    file = open(f"{username}.txt", "r")
    file.close()
```

The program tries to open the user's file.

If the file exists, the user exists.

* * *

## User Not Found

```python
except FileNotFoundError:
    print("User not found")
    return
```

If the file does not exist, the program prints:

```python
User not found
```

Here, `return` is used to stop the function.

This is better than `exit()` because `exit()` closes the whole program immediately.

* * *

## Reading Saved Password

```python
with open(f"{username}.txt", "r") as f:
    checkpass = f.readline()
```

This opens the user's file and reads the saved password.

The saved password is stored in:

```python
checkpass
```

* * *

## Checking Password

```python
if password == checkpass:
    print("Welcome")
else:
    print("Sorry, incorrect password")
```

If entered password and saved password are same, login is successful.

Otherwise, it prints incorrect password.

* * *

# 10\. Simpler Version Like Your Original Code

This is very close to your original code.

```python
def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except:
        print("User not found")
        return

    with open(f"{username}.txt", "r") as f:
        checkpass = f.readline()

        if password == checkpass:
            print("Welcome")
        else:
            print("Sorry, incorrect password")


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()
    else:
        login()


ask()
```

This version is okay for beginners.

But for better practice, this is preferred:

```python
except FileNotFoundError:
```

instead of only:

```python
except:
```

Because `except:` catches all errors, but `FileNotFoundError` catches only file-not-found error.

* * *

# 11\. Important Note About This Login System

This login system is only for learning.

It teaches:

```text
1. Function
2. Input
3. File handling
4. Try and except
5. User already exists
6. User not found
7. Password checking
```

But in real websites or real applications, passwords should not be saved directly like this.

In real projects, passwords should be hashed before saving.

For now, this is good for beginner-level Python file handling practice.

* * *

# 12\. Class Explanation Flow

You can explain the login system like this:

```text
When registering:
Python checks if username.txt exists.
If it exists, the user already exists.
If it does not exist, Python creates the file and saves the password.

When logging in:
Python checks if username.txt exists.
If it does not exist, user not found.
If it exists, Python reads the saved password.
Then it compares the saved password with the entered password.
```

* * *

# 13\. Day 3 Practice Questions

## List Slicing Questions

1.  Create a list of 10 numbers and print the first 5 numbers.
    
2.  Print the last 3 numbers from a list.
    
3.  Reverse a list using slicing.
    
4.  Print every second item from a list.
    

* * *

## Tuple Questions

1.  Create a tuple of five fruits and print each fruit.
    
2.  Create a tuple of numbers and find its length.
    
3.  Check whether `"Python"` exists in a tuple.
    
4.  Try to change a tuple item and observe the error.
    

* * *

## Dictionary Questions

1.  Create a dictionary for a student with name, age, class, and address.
    
2.  Create a dictionary for a product and calculate total price.
    
3.  Update the marks of a student in a dictionary.
    
4.  Print all keys and values from a dictionary.
    

* * *

## Set Questions

1.  Create a set of numbers with duplicate values and print it.
    
2.  Add a new item to a set.
    
3.  Remove an item from a set.
    
4.  Convert a list with duplicate values into a set.
    

* * *

## Exception Handling Questions

1.  Take two numbers and divide them. Handle `ZeroDivisionError`.
    
2.  Take age from user. Handle `ValueError`.
    
3.  Try to access an invalid list index. Handle `IndexError`.
    
4.  Try to access an invalid dictionary key. Handle `KeyError`.
    
5.  Try to read a file that does not exist. Handle `FileNotFoundError`.
    

* * *

## File Handling Questions

1.  Create a file named `message.txt` and write `"Hello Python"` into it.
    
2.  Read and print the content of `message.txt`.
    
3.  Append three student names into `students.txt`.
    
4.  Read a file and handle `FileNotFoundError`.
    

* * *

## Final Project Question

Create a login system using file handling.

Requirements:

```text
1. Register user.
2. Login user.
3. If user already exists, show message.
4. If user does not exist, show user not found.
5. If password is correct, show welcome.
6. If password is wrong, show incorrect password.
7. Use try and except.
8. Store each user password in username.txt file.
```

* * *

# 14\. Day 3 Final Summary

Today we learned:

```text
List slicing:
Used to get part of a list.

Tuple:
Used to store multiple values that should not change.

Dictionary:
Used to store data in key-value pairs.

Set:
Used to store unique values.

Exception handling:
Used to handle errors without crashing the program.

File handling:
Used to create, read, write, and append files.

Login system:
Used file handling and exception handling together.
```

Final simple memory:

```text
List      -> changeable collection
Tuple     -> unchangeable collection
Dictionary -> key-value collection
Set       -> unique value collection
try-except -> error handling
File      -> permanent data storage
```
