Skip to main content

Day 4 of python

Updated 8 min readMarkdown

1. Dictionary Concept

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

Example:

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

Here:

"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:

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

2. Accessing Dictionary Values

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

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

Output:

Ram
18
75

3. Updating Dictionary Values

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

student["marks"] = 85

print(student)

Output:

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

Here, marks changed from 75 to 85.


4. Simple Dictionary Exercise

Question

Create a dictionary named book.

It should store:

title
author
price

Then print all details.

Solution

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

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

Output:

Title: Python Basics
Author: Ram
Price: 500

5. Mini Project: Student Management System Using Dictionary

Project Goal

Create a simple program that can:

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

This project uses:

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

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

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:

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

Add Student

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

This stores user input inside the dictionary.


View Student

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

This displays the student details.


Update Marks

student["marks"] = new_marks

This changes old marks into new marks.


Check Result

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:

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

In dictionary, we write:

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:

Student class is a blueprint.

Object

An object is created from a class.

Example:

Class  -> Student
Object -> Ram
Object -> Sita

10. Simple OOP Example

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:

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:

Data is lost when the program closes.

In database:

Data can be stored permanently.

SQLite is a simple database that Python can use directly.

We use:

import sqlite3

SQLite creates a file like:

school.db

13. Very Simple SQLite Program

This program will:

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

Save as:

simple_db.py
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:

(1, 'Ram', 18, 75.0)

14. Simple Database Code Explanation

Import SQLite

import sqlite3

This lets us use SQLite in Python.


Connect to Database

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

This creates or opens the database file.


Cursor

cursor = connection.cursor()

Cursor is used to run SQL commands.

Simple meaning:

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

Create Table

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:

id
name
age
marks

Insert Data

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

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

This selects all data from the students table.

fetchall() gets all rows.


for student in students:
    print(student)

This prints each student record.


15. Only Remember This for Database Today

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:

brand
model
price

Print all details.


Practice 2: Student Management

Create a student management system using dictionary.

It should have:

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:

brand
model
price

Create one object and print details.


Practice 4: Database

Create a database named:

library.db

Create a table named:

books

Columns:

id
title
author
price

Then insert one book and select all books.


Final Summary

Today we learned:

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.

45 views

No comments yet. Be the first to comment.