# Day 4 of python

# 1\. Dictionary Concept

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

Example:

```plaintext
student = {
    "name": "Ram",
    "age": 18,
    "marks": 75
}

```

Here:

```plaintext
"name"  is key, "Ram" is value
"age"   is key, 18 is value
"marks" is key, 75 is value

```

Dictionary is useful when we want to store related information together.

Example:

```plaintext
One student has name, age, and marks.
So we can store these details in one dictionary.

```

* * *

# 2\. Accessing Dictionary Values

```plaintext
student = {
    "name": "Ram",
    "age": 18,
    "marks": 75
}

print(student["name"])
print(student["age"])
print(student["marks"])

```

Output:

```plaintext
Ram
18
75

```

* * *

# 3\. Updating Dictionary Values

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

student["marks"] = 85

print(student)

```

Output:

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

```

Here, marks changed from `75` to `85`.

* * *

# 4\. Simple Dictionary Exercise

## Question

Create a dictionary named `book`.

It should store:

```plaintext
title
author
price

```

Then print all details.

## Solution

```plaintext
book = {
    "title": "Python Basics",
    "author": "Ram",
    "price": 500
}

print("Title:", book["title"])
print("Author:", book["author"])
print("Price:", book["price"])

```

Output:

```plaintext
Title: Python Basics
Author: Ram
Price: 500

```

* * *

# 5\. Mini Project: Student Management System Using Dictionary

## Project Goal

Create a simple program that can:

```plaintext
1\. Add student details
2. View student details
3. Update marks
4. Check pass or fail
5. Exit

```

This project uses:

```plaintext
Dictionary
Function
Input
If else
While loop
Try except

```

This is a good continuation from Day 3 because students already studied dictionary, exception handling, file handling, and login using file handling.

* * *

# 6\. Full Code

```plaintext
student = {
    "name": "",
    "age": 0,
    "marks": 0
}

def add_student():
    try:
        name = input("Enter student name: ")
        age = int(input("Enter student age: "))
        marks = float(input("Enter student marks: "))

        student["name"] = name
        student["age"] = age
        student["marks"] = marks

        print("Student details added successfully")

    except ValueError:
        print("Please enter valid number for age and marks")

def view_student():
    if student["name"] == "":
        print("No student details found")
    else:
        print("\n--- Student Details ---")
        print("Name:", student["name"])
        print("Age:", student["age"])
        print("Marks:", student["marks"])

def update_marks():
    if student["name"] == "":
        print("No student details found")
    else:
        try:
            new_marks = float(input("Enter new marks: "))
            student["marks"] = new_marks
            print("Marks updated successfully")

        except ValueError:
            print("Please enter valid marks")

def check_result():
    if student["name"] == "":
        print("No student details found")
    else:
        if student["marks"] >= 40:
            print(student["name"], "has passed")
        else:
            print(student["name"], "has failed")

def menu():
    while True:
        print("\n===== Student Management System =====")
        print("1. Add Student")
        print("2. View Student")
        print("3. Update Marks")
        print("4. Check Result")
        print("5. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            add_student()

        elif choice == "2":
            view_student()

        elif choice == "3":
            update_marks()

        elif choice == "4":
            check_result()

        elif choice == "5":
            print("Program closed")
            break

        else:
            print("Invalid choice")

menu()

```

* * *

# 7\. Simple Project Explanation

## Student Dictionary

```plaintext
student = {
    "name": "",
    "age": 0,
    "marks": 0
}

```

This dictionary stores one student's details.

At first, the values are empty.

After adding student, it may look like this:

```plaintext
student = {
    "name": "Ram",
    "age": 18,
    "marks": 75
}

```

* * *

## Add Student

```plaintext
student["name"] = name
student["age"] = age
student["marks"] = marks

```

This stores user input inside the dictionary.

* * *

## View Student

```plaintext
print("Name:", student["name"])
print("Age:", student["age"])
print("Marks:", student["marks"])

```

This displays the student details.

* * *

## Update Marks

```plaintext
student["marks"] = new_marks

```

This changes old marks into new marks.

* * *

## Check Result

```plaintext
if student["marks"] >= 40:
    print(student["name"], "has passed")
else:
    print(student["name"], "has failed")

```

If marks are `40` or above, the student passes.

If marks are below `40`, the student fails.

* * *

# 8\. Basic OOP Introduction

OOP means **Object-Oriented Programming**.

Simple meaning:

```plaintext
OOP is a way to keep related data and functions together.

```

In dictionary, we write:

```plaintext
student = {
    "name": "Ram",
    "age": 18,
    "marks": 75
}

```

In OOP, we can create a `Student` class.

* * *

# 9\. Class and Object

## Class

A class is a blueprint.

Example:

```plaintext
Student class is a blueprint.

```

## Object

An object is created from a class.

Example:

```plaintext
Class  -> Student
Object -> Ram
Object -> Sita

```

* * *

# 10\. Simple OOP Example

```plaintext
class Student:
    def __init__(self, name, age, marks):
        self.name = name
        self.age = age
        self.marks = marks

    def show_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        print("Marks:", self.marks)

student1 = Student("Ram", 18, 75)

student1.show_details()

```

Output:

```plaintext
Name: Ram
Age: 18
Marks: 75

```

* * *

# 11\. Simple OOP Terms

| Term | Meaning |
| --- | --- |
| Class | Blueprint |
| Object | Real item created from class |
| Attribute | Variable inside object |
| Method | Function inside class |
| `__init__()` | Runs automatically when object is created |
| `self` | Current object |

* * *

# 12\. Very Simple Database Introduction

A database is used to store data permanently.

In dictionary:

```plaintext
Data is lost when the program closes.

```

In database:

```plaintext
Data can be stored permanently.

```

SQLite is a simple database that Python can use directly.

We use:

```plaintext
import sqlite3

```

SQLite creates a file like:

```plaintext
school.db

```

* * *

# 13\. Very Simple SQLite Program

This program will:

```plaintext
1\. Create database
2. Create table
3. Insert one student
4. Select and show students

```

Save as:

```plaintext
simple_db.py

```

```plaintext
import sqlite3

# Connect to database
connection = sqlite3.connect("school.db")

# Create cursor
cursor = connection.cursor()

# Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    age INTEGER,
    marks REAL
)
""")

# Insert one student
cursor.execute("""
INSERT INTO students (name, age, marks)
VALUES (?, ?, ?)
""", ("Ram", 18, 75))

# Save changes
connection.commit()

# Select data from table
cursor.execute("SELECT * FROM students")

students = cursor.fetchall()

for student in students:
    print(student)

# Close connection
connection.close()

```

Output example:

```plaintext
(1, 'Ram', 18, 75.0)

```

* * *

# 14\. Simple Database Code Explanation

## Import SQLite

```plaintext
import sqlite3

```

This lets us use SQLite in Python.

* * *

## Connect to Database

```plaintext
connection = sqlite3.connect("school.db")

```

This creates or opens the database file.

* * *

## Cursor

```plaintext
cursor = connection.cursor()

```

Cursor is used to run SQL commands.

Simple meaning:

```plaintext
Connection opens the database.
Cursor runs commands inside the database.

```

* * *

## Create Table

```plaintext
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    age INTEGER,
    marks REAL
)
""")

```

This creates a table named `students`.

Columns are:

```plaintext
id
name
age
marks

```

* * *

## Insert Data

```plaintext
cursor.execute("""
INSERT INTO students (name, age, marks)
VALUES (?, ?, ?)
""", ("Ram", 18, 75))

```

This adds one student into the table.

The `?` signs are placeholders.

Python safely puts values there.

* * *

## Select Data

```plaintext
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()

```

This selects all data from the students table.

`fetchall()` gets all rows.

* * *

## Print Data

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

```

This prints each student record.

* * *

# 15\. Only Remember This for Database Today

```plaintext
Database stores data permanently.

SQLite creates a .db file.

Table stores data in rows and columns.

CREATE TABLE creates a table.

INSERT INTO adds data.

SELECT reads data.

Cursor runs SQL commands.

```

* * *

# 16\. Final Practice

## Practice 1: Dictionary

Create a dictionary named `mobile`.

It should contain:

```plaintext
brand
model
price

```

Print all details.

* * *

## Practice 2: Student Management

Create a student management system using dictionary.

It should have:

```plaintext
1\. Add student
2. View student
3. Update marks
4. Check result
5. Exit

```

* * *

## Practice 3: OOP

Create a class named `Mobile`.

It should have:

```plaintext
brand
model
price

```

Create one object and print details.

* * *

## Practice 4: Database

Create a database named:

```plaintext
library.db

```

Create a table named:

```plaintext
books

```

Columns:

```plaintext
id
title
author
price

```

Then insert one book and select all books.

* * *

# Final Summary

Today we learned:

```plaintext
Dictionary stores data in key-value pairs.

Student Management System can be made using dictionary.

OOP keeps related data and functions together.

Class is a blueprint.

Object is created from class.

SQLite is a simple database.

CREATE TABLE creates a table.

INSERT INTO adds data.

SELECT reads data from table.

```
