Showing posts with label Learn Python. Show all posts
Showing posts with label Learn Python. Show all posts

Learn CRUD Operations in Python with SQLite – Beginner’s Tutorial with Code Examples

Basic CRUD Operations with Python and SQLite: A Simple and Fun Tutorial for Everyone

Imagine you have a magical notebook where you can write down your favorite toys, find them whenever you want, update their details, or even remove them if you don’t need them anymore. In the world of computers, this is what CRUD operations do with a database! CRUD stands for Create, Read, Update, and Delete—the four basic actions you can perform on data. In this tutorial, we’ll learn how to do these operations using Python and SQLite, a super simple database tool. We’ll keep it fun, easy to understand for a 6th grader, and useful for both beginners and experienced users, covering all the key aspects in about 1200 words.


๐Ÿ“š Table of Contents


What are CRUD Operations?

CRUD is like the four magic tricks you can do with your data:

  • Create: Add new information, like writing a new toy’s name in your notebook.
  • Read: Look up information, like finding all your toys in the notebook.
  • Update: Change information, like updating a toy’s price.
  • Delete: Remove information, like erasing a toy you gave away.

We’ll use Python (a friendly programming language) and SQLite (a lightweight database) to perform these tricks. SQLite is perfect because it’s simple, free, and works on your computer or even your phone. Let’s create a fun example: a database for a Toy Store to store toy names, types, and prices!


Why Use Python and SQLite for CRUD?

Python and SQLite are awesome because:

  • Easy to Learn: Python is like giving clear instructions to a friend, and SQLite is simple to use.
  • Lightweight: SQLite stores everything in one file, so you don’t need a big setup.
  • Free: Both are completely free, perfect for students and hobbyists.
  • Powerful: Even professionals use them for apps, games, and websites.
  • Fun: Managing data feels like organizing a treasure chest!

Whether you’re new to coding or a pro, CRUD operations with Python and SQLite are a great way to learn how to handle data.


Getting Started

To start, you need Python installed on your computer (download it from python.org if you don’t have it). SQLite comes built-in with Python, so you don’t need to install anything extra. We’ll write Python code to:

  1. Create a database and a table for our toy store.
  2. Perform CRUD operations to manage toy data.

You can write this code in a Python editor (like IDLE, VS Code, or even a simple text editor). If you prefer clicking instead of coding, you can also use DB Browser for SQLite to see your data visually, but we’ll focus on Python code for this tutorial.


Step 1: Setting Up the Database and Table

Before we do CRUD, we need a database and a table to store our toys. Our table will have:

  • ToyID: A unique number for each toy (SQLite assigns this automatically).
  • Name: The toy’s name (like “Robot”).
  • Type: The kind of toy (like “Action Figure” or “Puzzle”).
  • Price: How much the toy costs.

Here’s the code to create a database called toystore.db and a table called Toys:

import sqlite3

# Connect to the database (creates toystore.db if it doesn't exist)
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create a Toys table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Toys (
        ToyID INTEGER PRIMARY KEY,
        Name TEXT,
        Type TEXT,
        Price REAL
    )
''')

# Save changes and close the connection
conn.commit()
conn.close()

print("Database and Toys table created successfully!")

What’s Happening?

  • import sqlite3: Brings in SQLite tools for Python.
  • sqlite3.connect('toystore.db'): Creates or connects to a database file called toystore.db.
  • CREATE TABLE IF NOT EXISTS Toys: Makes a table called Toys with columns for ToyID, Name, Type, and Price. The PRIMARY KEY means each toy gets a unique ID.
  • conn.commit(): Saves your work, like clicking “Save” on a document.
  • conn.close(): Closes the database, like shutting your notebook.

Run this code, and you’ll see a toystore.db file in your folder. Now we’re ready for CRUD!


Step 2: Create (Adding Data)

The Create operation adds new data to the table. Let’s add three toys to our Toys table using the INSERT command.

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Add toys to the table
cursor.execute("INSERT INTO Toys (Name, Type, Price) VALUES ('Robot', 'Action Figure', 25.00)")
cursor.execute("INSERT INTO Toys (Name, Type, Price) VALUES ('Jigsaw', 'Puzzle', 10.00)")
cursor.execute("INSERT INTO Toys (Name, Type, Price) VALUES ('Teddy', 'Stuffed Animal', 15.00)")

# Save changes
conn.commit()

print("Toys added successfully!")

# Close the connection
conn.close()

What’s Happening?

  • INSERT INTO Toys: Adds a new row to the Toys table.
  • (Name, Type, Price): Specifies which columns we’re filling.
  • VALUES ('Robot', 'Action Figure', 25.00): The data for one toy. We skip ToyID because SQLite assigns it (1, 2, 3, etc.).
  • conn.commit(): Saves the toys to the database.

Now your table looks like this:

ToyIDNameTypePrice
1RobotAction Figure25.00
2JigsawPuzzle10.00
3TeddyStuffed Animal15.00

Step 3: Read (Finding Data)

The Read operation lets you look at data in the table. We’ll use the SELECT command to see our toys. Here are two examples: one to show all toys and one to find toys of a specific type.

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Read all toys
print("All Toys:")
cursor.execute("SELECT * FROM Toys")
all_toys = cursor.fetchall()
for toy in all_toys:
    print(toy)

# Read only Action Figures
print("\nAction Figures:")
cursor.execute("SELECT * FROM Toys WHERE Type = 'Action Figure'")
action_figures = cursor.fetchall()
for toy in action_figures:
    print(toy)

# Close the connection
conn.close()

What’s Happening?

  • SELECT * FROM Toys: Gets all columns and rows from the Toys table.
  • cursor.fetchall(): Grabs all the data as a list.
  • SELECT * FROM Toys WHERE Type = 'Action Figure': Finds only toys where the Type is “Action Figure.”
  • print(toy): Shows each toy’s details.

When you run this, you’ll see:

All Toys:
(1, 'Robot', 'Action Figure', 25.0)
(2, 'Jigsaw', 'Puzzle', 10.0)
(3, 'Teddy', 'Stuffed Animal', 15.0)

Action Figures:
(1, 'Robot', 'Action Figure', 25.0)

Step 4: Update (Changing Data)

The Update operation changes existing data. Let’s say the price of the Robot toy went up to $30.00. We’ll use the UPDATE command.

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Update the price of the Robot
cursor.execute("UPDATE Toys SET Price = 30.00 WHERE Name = 'Robot'")

# Save changes
conn.commit()

# Check the updated data
cursor.execute("SELECT * FROM Toys WHERE Name = 'Robot'")
updated_toy = cursor.fetchone()
print("Updated Robot:", updated_toy)

# Close the connection
conn.close()

What’s Happening?

  • UPDATE Toys SET Price = 30.00: Changes the Price column to 30.00.
  • WHERE Name = 'Robot': Only updates the toy named “Robot.”
  • cursor.fetchone(): Gets just one row (the updated Robot).

Output:

Updated Robot: (1, 'Robot', 'Action Figure', 30.0)

Now the Robot’s price is $30.00 in the table.


Step 5: Delete (Removing Data)

The Delete operation removes data. Let’s say we sold the Jigsaw puzzle and want to remove it from the table. We’ll use the DELETE command.

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Delete the Jigsaw toy
cursor.execute("DELETE FROM Toys WHERE Name = 'Jigsaw'")

# Save changes
conn.commit()

# Check the remaining toys
cursor.execute("SELECT * FROM Toys")
remaining_toys = cursor.fetchall()
print("Remaining Toys:")
for toy in remaining_toys:
    print(toy)

# Close the connection
conn.close()

What’s Happening?

  • DELETE FROM Toys WHERE Name = 'Jigsaw': Removes the row where the Name is “Jigsaw.”
  • SELECT * FROM Toys: Shows the remaining toys.

Output:

Remaining Toys:
(1, 'Robot', 'Action Figure', 30.0)
(3, 'Teddy', 'Stuffed Animal', 15.0)

The Jigsaw toy is gone!


Putting It All Together

Here’s a single program that does all four CRUD operations:

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create: Add a new toy
cursor.execute("INSERT INTO Toys (Name, Type, Price) VALUES ('Car', 'Model', 20.00)")
conn.commit()
print("Added Car toy!")

# Read: Show all toys
cursor.execute("SELECT * FROM Toys")
print("\nAll Toys:")
for toy in cursor.fetchall():
    print(toy)

# Update: Change Teddy's price to $18.00
cursor.execute("UPDATE Toys SET Price = 18.00 WHERE Name = 'Teddy'")
conn.commit()
print("\nUpdated Teddy's price!")
cursor.execute("SELECT * FROM Toys WHERE Name = 'Teddy'")
print(cursor.fetchone())

# Delete: Remove the Car toy
cursor.execute("DELETE FROM Toys WHERE Name = 'Car'")
conn.commit()
print("\nDeleted Car toy!")
cursor.execute("SELECT * FROM Toys")
print("Remaining Toys:")
for toy in cursor.fetchall():
    print(toy)

# Close the connection
conn.close()

This code shows all four operations in action, and you can run it to see the results.


Tips for Success

  1. Start Small: Try CRUD with a simple table, like our toy store.
  2. Practice SQL: Learn commands like INSERT, SELECT, UPDATE, and DELETE. They’re like magic words!
  3. Check Your Data: Always use SELECT to make sure your changes worked.
  4. Backup Your Database: Copy your .db file to keep your data safe.
  5. Explore: Try making a table for your favorite books, games, or pets!

Why Learn CRUD?

Learning CRUD with Python and SQLite is awesome because:

  • It’s Fun: Managing data is like organizing a treasure chest.
  • It’s Useful: You can use it for apps, games, or school projects.
  • It’s a Big Skill: CRUD is the foundation of working with databases, used in websites, apps, and more.
  • It’s Easy: Python and SQLite make it simple to start.

Common Questions

1. Do I need to know coding to use CRUD?

A little coding helps, but tools like DB Browser for SQLite let you do CRUD with clicks. Python makes it more flexible.

2. Can I use SQLite for big projects?

SQLite is great for small to medium projects. For huge websites, you might need MySQL or PostgreSQL.

3. Is SQLite safe?

Yes, it’s very reliable, but always back up your .db file.

4. What else can I do with CRUD?

You can build apps, store game scores, or even track your homework!


Wrapping Up

CRUD operations with Python and SQLite are like learning to add, find, change, and remove items from a magical notebook. In this tutorial, we created a toy store database, added toys, read their details, updated prices, and deleted toys—all with simple Python code. Whether you’re a 6th grader or an experienced coder, CRUD is a fun and powerful skill to learn.

Try creating your own database for something you love, like movies or Pokรฉmon. Play with the code, explore more SQL commands, or try DB Browser for SQLite to see your data visually. With Python and SQLite, you’re ready to organize data like a pro!

Happy coding, and enjoy your CRUD adventures!


๐ŸŽ“ Ready for More Python Fun?

Check out more tutorials Next!

๐Ÿ’ฌ Have a question? Leave a comment below or reach out to us!

๐Ÿ”” Don’t forget to bookmark this page and share it with friends learning Python!


Top 10 Python Projects for Beginners (With Source Code and GitHub Links)

← Back to Home

 

๐Ÿ Top 10 Python Projects for Beginners (With Source Code and Diagrams)

Are you just starting out with Python and wondering what projects to build? Working on hands-on projects is one of the most effective ways to solidify your programming skills. In this blog post, we’ll explore 10 beginner-friendly Python projects, each with a diagram and source code to get you coding right away!


✅ 1. Number Guessing Game

๐Ÿ’ก Concept Diagram:

[Start] → [Generate Random Number] → [User Guesses] → [Check Guess]
   → [Too High/Low?] → [Try Again] → [Correct?] → [End]

๐Ÿง  What You'll Learn:

  • Loops

  • Conditional statements

  • Random module

๐Ÿงพ Source Code:

import random

number = random.randint(1, 100)
guess = None

while guess != number:
    guess = int(input("Guess a number between 1 and 100: "))
    if guess < number:
        print("Too low!")
    elif guess > number:
        print("Too high!")
    else:
        print("Congratulations! You guessed it.")

✅ 2. Simple Calculator

๐Ÿ’ก Concept Diagram:

[Input Num1] + [Input Operator] + [Input Num2] → [Perform Operation] → [Display Result]

๐Ÿง  What You'll Learn:

  • Functions

  • Basic arithmetic

  • Input handling

๐Ÿงพ Source Code:

def calculator():
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    if operator == '+':
        print(num1 + num2)
    elif operator == '-':
        print(num1 - num2)
    elif operator == '*':
        print(num1 * num2)
    elif operator == '/':
        print(num1 / num2)
    else:
        print("Invalid operator")

calculator()

✅ 3. To-Do List (Console-Based)

๐Ÿ’ก Concept Diagram:

[Menu] → [Add Task / View Tasks / Delete Task] → [List Updated]

๐Ÿง  What You'll Learn:

  • Lists

  • Menu-driven programs

๐Ÿงพ Source Code:

tasks = []

def show_menu():
    print("\n1. Add Task\n2. View Tasks\n3. Delete Task\n4. Exit")

while True:
    show_menu()
    choice = input("Enter choice: ")

    if choice == '1':
        task = input("Enter task: ")
        tasks.append(task)
    elif choice == '2':
        for i, task in enumerate(tasks):
            print(f"{i+1}. {task}")
    elif choice == '3':
        index = int(input("Enter task number to delete: ")) - 1
        if 0 <= index < len(tasks):
            tasks.pop(index)
        else:
            print("Invalid task number.")
    elif choice == '4':
        break
    else:
        print("Invalid choice.")

✅ 4. Dice Roller Simulator

๐Ÿ’ก Concept Diagram:

[Press Enter] → [Generate Random Number (1-6)] → [Display Dice Face]

๐Ÿง  What You'll Learn:

  • Random numbers

  • Loop control

๐Ÿงพ Source Code:

import random

while input("Roll the dice? (y/n): ").lower() == 'y':
    print(f"You rolled a {random.randint(1, 6)}")

✅ 5. Countdown Timer

๐Ÿ’ก Concept Diagram:

[Input Time] → [Countdown Loop] → [Time's Up]

๐Ÿง  What You'll Learn:

  • Time module

  • Loops

๐Ÿงพ Source Code:

import time

t = int(input("Enter time in seconds: "))

while t:
    mins, secs = divmod(t, 60)
    print(f'{mins:02d}:{secs:02d}', end='\r')
    time.sleep(1)
    t -= 1

print("Time's up!")

✅ 6. Basic Contact Book

๐Ÿ’ก Concept Diagram:

[Menu] → [Add/View/Delete Contact] → [Dictionary Update]

๐Ÿง  What You'll Learn:

  • Dictionaries

  • Functions

  • File handling (Optional)

๐Ÿงพ Source Code:

contacts = {}

def add_contact():
    name = input("Name: ")
    phone = input("Phone: ")
    contacts[name] = phone

def view_contacts():
    for name, phone in contacts.items():
        print(f"{name}: {phone}")

while True:
    print("\n1. Add\n2. View\n3. Exit")
    choice = input("Choice: ")
    if choice == '1':
        add_contact()
    elif choice == '2':
        view_contacts()
    elif choice == '3':
        break

✅ 7. Password Generator

๐Ÿ’ก Concept Diagram:

[Input Length] → [Randomly Select Characters] → [Display Password]

๐Ÿง  What You'll Learn:

  • random and string modules

  • String manipulation

๐Ÿงพ Source Code:

import random
import string

length = int(input("Enter password length: "))
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
print("Generated password:", password)

✅ 8. QR Code Generator

๐Ÿ’ก Concept Diagram:

[Input Text/URL] → [Generate QR Image] → [Save File]

๐Ÿง  What You'll Learn:

  • External libraries (qrcode)

๐Ÿงพ Source Code:

pip install qrcode
import qrcode

data = input("Enter data to encode: ")
img = qrcode.make(data)
img.save("qrcode.png")
print("QR code saved as qrcode.png")

✅ 9. Weather App (Using API)

๐Ÿ’ก Concept Diagram:

[Input City] → [Fetch from OpenWeatherMap API] → [Display Weather]

๐Ÿง  What You'll Learn:

  • APIs

  • JSON parsing

  • requests module

๐Ÿงพ Source Code:

pip install requests
import requests

API_KEY = "your_api_key_here"
city = input("Enter city: ")
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

response = requests.get(url)
data = response.json()

if data.get('main'):
    print(f"Temperature: {data['main']['temp']}°C")
else:
    print("City not found.")

✅ 10. Tic-Tac-Toe (2 Player Game)

๐Ÿ’ก Concept Diagram:

[Player 1 & 2 Turn] → [Update Board] → [Check Winner/Draw] → [Repeat]

๐Ÿง  What You'll Learn:

  • Lists

  • Game logic

  • Conditions

๐Ÿงพ Source Code:

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 5)

def check_winner(board):
    for row in board:
        if row.count(row[0]) == 3 and row[0] != ' ':
            return row[0]
    for col in range(3):
        if board[0][col] == board[1][col] == board[2][col] != ' ':
            return board[0][col]
    if board[0][0] == board[1][1] == board[2][2] != ' ':
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] != ' ':
        return board[0][2]
    return None

board = [[" "]*3 for _ in range(3)]
turn = "X"

for _ in range(9):
    print_board(board)
    row = int(input(f"{turn}'s turn. Enter row (0-2): "))
    col = int(input(f"{turn}'s turn. Enter col (0-2): "))
    if board[row][col] == " ":
        board[row][col] = turn
        winner = check_winner(board)
        if winner:
            print_board(board)
            print(f"{winner} wins!")
            break
        turn = "O" if turn == "X" else "X"
    else:
        print("Cell already taken.")
else:
    print("It's a draw!")

๐Ÿ”š Final Thoughts

Each of these projects helps you practice essential Python concepts while having fun. Start with one, tweak it, break it, fix it — and watch your Python skills grow!

๐Ÿง  Click Next:  to explore the list of 100 python projects for beginners, intermediate and Expert level!


Top 3 Python Script Mode Projects for Beginners – Calculator, Quiz Game & Number Checker

← Back to Home

 

๐Ÿ Python Script Mode Projects for Students – Simple & Fun Assignments

If you're just starting out with Python, learning through small projects is a great way to build your skills and confidence. Below are three beginner-level Python projects you can write and run using Script Mode.

These projects are ideal for:

  • Practice

  • School/college assignments

  • Building confidence with Python programming


๐Ÿ“ What You’ll Learn:

  • How to write a Python script in Script Mode

  • How to save, run, and test .py files

  • Real examples with download links for .py files


๐Ÿงฎ 1. Simple Calculator in Python

This script allows users to perform basic operations like addition, subtraction, multiplication, and division.

๐Ÿ’ก Features:

  • Menu-based interface

  • Input from user

  • Error handling for division by zero

✅ Sample Code:

# calculator.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Cannot divide by zero"
    return x / y

print("Select operation:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
    print("Result:", add(num1, num2))
elif choice == '2':
    print("Result:", subtract(num1, num2))
elif choice == '3':
    print("Result:", multiply(num1, num2))
elif choice == '4':
    print("Result:", divide(num1, num2))
else:
    print("Invalid input")

๐Ÿง  2. Quiz Game in Python

A fun multiple-choice quiz with score tracking.

✅ Sample Code:

# quiz_game.py

score = 0

print("Welcome to the Python Quiz!\n")

answer1 = input("Q1: What is the keyword to define a function in Python? \n(a) def\n(b) function\n(c) fun\nAnswer: ")
if answer1.lower() == "a" or answer1.lower() == "def":
    score += 1

answer2 = input("Q2: What data type is used to store True or False? \n(a) int\n(b) bool\n(c) str\nAnswer: ")
if answer2.lower() == "b" or answer2.lower() == "bool":
    score += 1

answer3 = input("Q3: What symbol is used for comments in Python? \n(a) //\n(b) <!-- -->\n(c) #\nAnswer: ")
if answer3.lower() == "c" or answer3.lower() == "#":
    score += 1

print(f"\nYour final score is {score}/3")

๐Ÿ” 3. Even or Odd Number Checker

A very basic utility to check if a number is even or odd.

✅ Sample Code:

# number_checker.py

number = int(input("Enter a number: "))

if number % 2 == 0:
    print("The number is EVEN.")
else:
    print("The number is ODD.")


๐Ÿ“š How to Use These Scripts (Script Mode Guide)

  1. create and SAVE the scripts the files.

  2. Open any file (e.g., calculator.py) in a text editor or Python IDE.

  3. Save it if you make changes.

  4. Run the script:

    • Using Terminal:

      python calculator.py
      
    • Using IDLE:
      F5 to run.


๐ŸŽ“ Final Tip for Students

These small Python projects help you:

  • Practice Script Mode usage

  • Understand input/output

  • Write if-else logic

  • Build confidence in Python basics

Once you're comfortable, try adding:

  • More math operations to the calculator

  • Timer or difficulty levels to the quiz

  • Prime number or palindrome checkers in the number tool

๐Ÿง  Click Next:  to explore the list of 100 python projects for beginners, intermediate and Expert level!


Python Iterators: Understanding Iterables and Iterators in Python

← Back to Home

๐Ÿ” Python Iterators (Made Simple) 

Iterators are a way to go through all the elements in a collection (like a list or tuple), one item at a time. Python has built-in support for iterators, making it easy to loop through data.

If you've ever used a for loop in Python, you've already worked with iterators—even if you didn’t realize it!


✅ What Is an Iterator?

An iterator is an object that can be looped through (iterated over). It must follow two main rules:

  1. It must have a method called __iter__() → returns the iterator object itself.

  2. It must have a method called __next__() → returns the next item from the sequence.


๐Ÿ“˜ Example 1: Using an Iterator

my_list = [1, 2, 3]

# Get an iterator
my_iter = iter(my_list)

print(next(my_iter))  # Output: 1
print(next(my_iter))  # Output: 2
print(next(my_iter))  # Output: 3

๐Ÿ” Output:

1
2
3

If you call next() again after the list is finished, it will raise a StopIteration error.


๐Ÿ›  Behind the Scenes of a For Loop

When we use a for loop like this:

for item in [1, 2, 3]:
    print(item)

Python automatically:

  • Calls iter() to get an iterator.

  • Calls next() repeatedly until StopIteration is raised.


๐Ÿงฑ Building a Custom Iterator

Let’s create our own iterator to return numbers from 1 to 5.

๐Ÿ“˜ Example 2: Custom Iterator

class MyNumbers:
    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        if self.num <= 5:
            x = self.num
            self.num += 1
            return x
        else:
            raise StopIteration

# Create object
nums = MyNumbers()
my_iter = iter(nums)

for number in my_iter:
    print(number)

๐Ÿ” Output:

1
2
3
4
5

๐Ÿ’ก Important Notes

  • iter() creates an iterator from an iterable (like a list or string).

  • next() returns the next value.

  • When there are no more items, StopIteration is raised to end the loop.

  • You can create custom iterators by defining __iter__() and __next__().


๐Ÿ“˜ Example 3: Iterating Over a String

Strings are also iterable!

my_str = "Hi"
my_iter = iter(my_str)

print(next(my_iter))  # Output: H
print(next(my_iter))  # Output: i

๐Ÿ” Output:

H
i

๐ŸŽฏ Conclusion

Iterators are a powerful tool in Python that let you go through items one at a time. Whether you’re working with lists, strings, or building custom sequences, understanding iterators helps us write clean and efficient code.


Python Inheritance

← Back to Home

 

๐Ÿ Inheritance in Python (Made Simple)

Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows a class to use the properties and methods of another class.

Inheritance allows us to define a class that inherits all the methods and properties from another class.


Think of it like a family: a child can inherit features from their parents.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

 In programming, a class (child) can inherit features (methods and variables) from another class (parent).

For more on Python classes, check out our post on Python Classes and Objects.


✅ Why Use Inheritance?

  • To reuse code.

  • To make the program easier to manage.

  • To follow the DRY principle (Don't Repeat Yourself).


๐Ÿงฑ Basic Syntax

class Parent:
    # parent class
    pass

class Child(Parent):
    # child class that inherits from Parent
    pass

๐Ÿ“˜ Example: Simple Inheritance

# Parent class
class Animal:
    def speak(self):
        print("I am an animal")

# Child class
class Dog(Animal):
    def bark(self):
        print("Woof!")

# Creating object of Dog
my_dog = Dog()

my_dog.speak()  # Inherited from Animal
my_dog.bark()   # Defined in Dog

๐Ÿ” Output:

I am an animal
Woof!

Here, the Dog class inherits the speak() method from the Animal class. It also has its own method called bark().


๐Ÿ“˜ Example 2: Inheriting from a Person Class

Let’s create a simple example where a Student class inherits from a Person class.

๐Ÿ‘จ‍๐Ÿ‘ฉ‍๐Ÿ‘ง‍๐Ÿ‘ฆ Step 1: Create the Parent Class

# Parent class
class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

# Creating an object of Person
x = Person("Steve", "Tendulkar")
x.printname()

๐Ÿ” Output:

Steve Tendulkar

๐Ÿง’ Step 2: Create the Child Class

# Child class that inherits from Person
class Student(Person):
    pass  # No additional code, just inheriting everything from Person

# Creating an object of Student
x = Student("Mike", "Olsen")
x.printname()

๐Ÿ” Output:

Mike Olsen

๐Ÿ“ Note:
The pass keyword is used when you don't want to add any extra functionality to the child class. The Student class automatically gets all the properties and methods from the Person class.



๐Ÿ”„ Types of Inheritance in Python

  1. Single Inheritance – One child inherits from one parent.

  2. Multiple Inheritance – One child inherits from multiple parents.

  3. Multilevel Inheritance – A child inherits from a parent, and another child inherits from that child.

  4. Hierarchical Inheritance – Multiple children inherit from one parent.

  5. Hybrid Inheritance – A mix of any of the above types.


๐Ÿงช Example: Multiple Inheritance

class Father:
    def skill(self):
        print("Good at driving")

class Mother:
    def talent(self):
        print("Good at cooking")

class Child(Father, Mother):
    def hobby(self):
        print("Loves painting")

c = Child()
c.skill()
c.talent()
c.hobby()

๐Ÿ” Output:

Good at driving
Good at cooking
Loves painting

๐Ÿ’ก Important Points

  • The super() function is used to call methods from the parent class.

  • Inheritance makes your code organized and reusable.

  • If both parent and child have the same method, the child’s method will override the parent’s method.


๐Ÿ›  Using super() Example

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        super().speak()
        print("Dog barks")

d = Dog()
d.speak()

๐Ÿ” Output:

Animal speaks
Dog barks

๐ŸŽฏ Conclusion

Inheritance helps us write cleaner and more efficient code. Once we understand it, we can build complex applications more easily by reusing and extending existing code.

For more on Python classes, check out our post on Python Classes and Objects.

Python File Handling

← Back to Home


๐Ÿ”น File Handling in Python – Beginner-Friendly 

In Python, file handling allows us to create, read, write, and delete files. This is useful when you want to store data permanently, such as saving user info, logs, reports, etc.


๐Ÿ”ธ Why is File Handling Important?

Without file handling, data disappears when the program ends. With files, we can store and retrieve data even after the program stops.


๐Ÿ”ธ Opening a File

Python uses the built-in open() function to open a file.

Syntax:

file = open("filename", "mode")

Mode Description
'r' Read (default)
'w' Write (creates new or overwrites file)
'a' Append (adds to end of file)
'x' Create (fails if file exists)
'b' Binary mode (e.g., 'rb', 'wb')

๐Ÿ”ธ Example 1: Writing to a File


file = open("example.txt", "w")  # Open in write mode
file.write("Hello, this is a test.\n")
file.write("Writing to a file in Python.\n")
file.close()  # Always close the file!

๐Ÿ“ This creates a file named example.txt and writes two lines to it.


๐Ÿ”ธ Example 2: Reading from a File

file = open("example.txt", "r")  # Open in read mode
content = file.read()
print(content)
file.close()

๐Ÿ“ This reads and prints the contents of example.txt.


๐Ÿ”ธ Example 3: Appending to a File

file = open("example.txt", "a")  # Open in append mode
file.write("Adding a new line.\n")
file.close()

๐Ÿ“ This adds a new line at the end of the file without deleting the old content.


๐Ÿ”ธ Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())      # Here, strip() removes newline characters
file.close()

๐Ÿ”ธ Using with Statement (Recommended)

Python provides a cleaner way to handle files using the with statement. It automatically closes the file.

Example:

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

Using this way, you don’t need to call file.close().


๐Ÿ”ธ Deleting a File

You can delete a file using the os module.

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File does not exist.")

๐Ÿ”š Summary

  • Use open() to work with files.

  • Modes: 'r' (read), 'w' (write), 'a' (append), 'x' (create).

  • Always close the file after use (or use with).

  • Use the os module for file operations like deleting or checking existence.


✅ Quick Tip:

Use with open(...) as f: whenever possible—it’s safer and cleaner.

Python Exception Handling

← Back to Home

๐Ÿ›ก️ Exception Handling in Python: Advanced Guide for Beginners

In programming, exceptions are errors that happen when the program is running. Exceptions are runtime errors that disrupt normal flow. 

If we don’t handle these errors, our program might crash. Python gives us a way to catch and handle exceptions, which  helps catch these errors so the program can continue to run gracefully or show a friendly message to the user.


๐Ÿค” Why Use Exception Handling?

Consider a program that divides two user-input numbers. If a user inputs 0 as the divisor, a division by zero error (ZeroDivisionError) occurs. Without handling, your program crashes. With exception handling, you can:

  • Rescue the program from crashing

  • Display helpful error messages

  • Prevent invalid data from breaking your logic


๐Ÿงฉ Core Syntax

try:
    # code that may raise an exception
except SpecificError as e:
    # handle the error
else:
    # optional: runs when no exception was raised
finally:
    # optional: runs regardless, commonly used for clean-up


  • try: Wrap potentially risky operations

  • except: Catch and handle one or more specific exceptions

  • else: Execute only if no exceptions occur

  • finally: Always execute (e.g., closing files or releasing resources)


Let’s understand this with an example.

 

๐Ÿ”ธ Example 1: Division Program



๐Ÿ’ก Output Scenarios:

1.    Normal input:

                       


    2. Division by zero:

                



    3. Invalid Input:




๐Ÿงช Example: User Input & Division (Code block)

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
except ValueError:
    print("Error: Please enter a valid integer.")
else:
    print(f"Result: {result}")
finally:
    print("Operation complete.")

How this works:

  • ZeroDivisionError: Caught when divisor is zero

  • ValueError: Non-integer input

  • else: Displays result if no error

  • finally: Runs every time


๐Ÿ“š Common Built-in Exceptions

  • ZeroDivisionError – division by zero

  • ValueError – conversion errors

  • TypeError – unsupported operations

  • FileNotFoundError – file operations fail


๐Ÿง  Best Practices

  1. Catch only specific exceptions (e.g., ZeroDivisionError, not a general Exception)

  2. Avoid bare except:, which hides unexpected errors.

  3. Keep try blocks minimal – include only code that might fail

  4. Use finally for cleanup – close files or release resources.

  5. Log or print exception details using except Exception as e: for debugging purposes


๐Ÿ”ง Advanced Patterns: Raising and Chaining Exceptions

You can also raise custom exceptions or re-raise caught ones:

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError as e:
        raise ValueError("Invalid division") from e

This approach wraps an internal error in a clearer, higher-level exception—while preserving original context.


๐Ÿ“Œ Summary

  • Use try to wrap code that might cause an error.

  • Use Except to Handle specific exceptions to maintain clarity

  • Use else for code that runs only if there's no error and success paths.

  •  Use finally for code that should run no matter what (like essential cleanup).

  • Apply best practices to write robust, maintainable code.


Exception handling makes your program more reliable and user-friendly

Mastering exception handling transforms your scripts from fragile to resilient—making them suitable for real-world applications!


Python Classes and Objects

← Back to Home


๐Ÿ”น Classes and Objects in Python

Python is an object-oriented programming (OOP) language. This means it allows you to create and use classes and objects—which helps you organize and reuse code easily.



๐Ÿ”ธ What is a Class?

A class is like a blueprint for creating objects. Think of a class as a design for a car. It defines what a car is (wheels, engine, doors), but it's not a real car yet.

A class is a code template for creating objects. 

Objects have member variables and have behavior associated with them. 

In python, a class is created by the keyword class.

Example:

class Car:
    # attributes and methods go here
    pass


๐Ÿ”ธ What is an Object?

An object is a real-world instance of a class. If a class is the blueprint, then an object is the actual car built using that blueprint.

Example:

my_car = Car()

Now my_car is an object of the Car class.



๐Ÿ”ธ Let’s Build a Real Example

Let’s create a class that represents a Person with a name and age, and a method to display their info.

✅ Example:

class Person:
    def __init__(self, name, age):
        self.name = name      # attribute
        self.age = age        # attribute

    def greet(self):          # method
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating objects
person1 = Person("Surya", 25)
person2 = Person("Pawan", 30)

# Calling methods
person1.greet()
person2.greet()

๐Ÿ’ก Output:

Hello, my name is Surya and I am 25 years old.
Hello, my name is Pawan
and I am 30 years old.

๐Ÿ”ธ Breaking It Down

Part Description
class Person: Defines a class called Person
__init__ A special method called a constructor; runs when you create an object
self Refers to the current object (must be the first parameter in methods)
self.name = name Assigns the input to the object's attribute
greet() A method that prints a message using the object’s data

๐Ÿ”ธ Another Example: A Simple Bank Account

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"{amount} deposited. New balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"{amount} withdrawn. New balance: {self.balance}")
        else:
            print("Insufficient balance!")

# Create an account
account = BankAccount("John", 1000)

# Use the methods
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)

๐Ÿ’ก Output:

500 deposited. New balance: 1500
300 withdrawn. New balance: 1200
Insufficient balance!

๐Ÿ”š Summary

  • A class defines the structure and behavior (attributes and methods).

  • An object is a real example of the class.

  • Use __init__ to initialize object attributes.

  • Use self to refer to the current object inside the class.

  • Classes help keep your code organized, reusable, and clean.


Creating a simple Function in python || python code for creating function

← Back to Home

๐Ÿ”น Functions in Python

A function is a block of code which only runs when it is called.

we can pass data, known as parameters, into a function.

A function can return data as a result.


# In Python a function is defined using the def keyword:

๐Ÿ”ธ Example : Creating a Function

def my_function():
  print("Hello function" )



๐Ÿ”ธ  Calling a Function

To call a function, we use the function name followed by parenthesis

 Example :


def my_function():
  print("Hello from function")

my_function()    # Here is Function call by its name


Python Functions Explained: A Beginner’s Guide with Code Examples

← Back to Home

๐Ÿ” Understanding Python Functions – A Beginner’s Guide

Functions are one of the most powerful and useful features in Python. They allow you to group code into reusable blocks, making your programs more organized, readable, and efficient.

Functions are the heart of clean, efficient Python programming. If you're a beginner, think of functions as named blocks of code that do something specific — like a recipe in a cookbook.


๐Ÿง  What is a Function?

A function is a reusable block of code that  that performs a specific task and runs only when called.  You define it once and call it whenever needed. 

You can pass data into it using parameters, and get a result back using the return keyword.

๐Ÿ“Œ Key Points:

  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.
  • In Python, a function is defined using the def keyword:

See example below:

def my_function():
  print("Hello from a function")

๐Ÿ”ง Basic Anatomy of a Function

def function_name(parameters):
    # code block
    return result

๐Ÿ‘️ Code Diagram

+---------------------------+
| def greet(name):         | <- Function Definition
|     print("Hello", name) | <- Function Body
+---------------------------+

        ⬇ Function Call

+--------------------+
| greet("Alice")     | <- Output: Hello Alice
+--------------------+

✅ Why Use Functions?

Functions help you:

๐Ÿงฉ Break complex tasks into manageable chunks
๐Ÿ” Reuse code instead of repeating
๐Ÿ“š Improve readability of your code
๐Ÿ› ️ Debug and maintain programs easily


✍️ Creating Your First Function

Let’s write a simple function:

def my_function():
    print("Hello from a function")

✍️ Defining and Calling a Function

Let’s write a above simple function again:

def my_function():
    print("Hello from a function!")

# Call the function
my_function()

๐Ÿ–ฅ️ Output:

Hello from a function!


๐Ÿงพ Function with Parameters

def greet(name):
    print(f"Hello, {name}!")
    
greet("Alice")

๐Ÿ–ฅ️ Output:

Hello, Alice!

๐Ÿ“Œ You can pass any data—strings, numbers, lists, etc.—as parameters.



๐Ÿ” Reusability at Work:

Want to greet different users? Use parameters.

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

๐Ÿ–จ️ Output:

Hello, Alice!
Hello, Bob!

๐Ÿ”„ Returning Values from Functions

Some functions return a result:

def add(a, b):
    return a + b

sum = add(4, 6)
print(sum)

๐Ÿ–จ️ Output:

10


๐Ÿ”„ Function with Conditional Logic

def is_even(num):
    if num % 2 == 0:
        return True
    else:
        return False

print(is_even(4))  # True
print(is_even(5))  # False

๐Ÿ“Œ You can use functions to implement logic and decision-making.


๐Ÿงญ Flowchart: How a Function Works

[Start]
   ↓
Define Function → [Call Function?] — No → [End]
                          ↓ Yes
                    Execute Code Block
                          ↓
                     Return (Optional)
                          ↓
                        [End]

See the flowchart in picture below:




๐ŸŽฅ Watch and Learn

Want to see it in action?
๐Ÿ‘‰ Check out the video below: “What is a Function in Python” – ideal for visual learners!



๐ŸŽฏ Final Tip

Functions help you write clean, modular, and testable code. The more you use them, the better your Python skills will become!


๐Ÿš€ Your Turn

Now that you know the basics of Python functions, try creating your own! Whether it’s a calculator or a greeting app, functions will help you build smarter and cleaner code.


Python Lambda Function Explained with Examples – Simple Guide for learners

← Back to Home

๐Ÿ Python Lambda Function Explained – Easy Guide for Students & Professionals

Lambda functions in Python are small, powerful, and often misunderstood — but once you get the hang of them, they become a valuable tool in your coding toolkit.

In this guide, we’ll explain what lambda functions are, when to use them, how to write them, and some real-world examples. Whether you’re a beginner or a working professional, this article will help you master Python’s anonymous functions.


✅ What is a Lambda Function in Python?

A lambda function is a small, anonymous function defined using the keyword lambda.

It is:

  • Used for short, one-line functions

  • Often used where a function is needed temporarily

  • Can take any number of arguments but has only one expression

  • Lambda functions are anonymous functions in Python used for quick operations.

  • You can use a lambda function in map() and filter() to simplify logic.

  • They are especially useful in functional programming with Python.


๐Ÿง  Syntax of Lambda Function

lambda arguments: expression

This returns a function object that you can call just like a normal function.


๐Ÿงช Basic Example

Let’s write a lambda function that adds 10 to a number:

add_ten = lambda x: x + 10
print(add_ten(5))  # Output: 15

Here, lambda x: x + 10 is equivalent to:

def add_ten(x):
    return x + 10

๐Ÿ” Multiple Arguments Example

multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

⚙️ Where to Use Lambda Functions

Lambda functions are most commonly used:

  • Inside map(), filter(), and reduce()

  • When passing a simple function as an argument

  • To simplify short logic without cluttering the code


๐Ÿงฉ Lambda with map()

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # Output: [1, 4, 9, 16]

๐Ÿงช Lambda with filter()

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # Output: [2, 4, 6]

➕ Lambda with sorted()

students = [('Alice', 85), ('Bob', 72), ('Charlie', 90)]
# Sort by score (second element)
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 72), ('Alice', 85), ('Charlie', 90)]

⚠️ When NOT to Use Lambda

  • For complex logic (use def instead)

  • When readability is more important than brevity

  • If the function needs a docstring or name


๐Ÿ“ Summary Table

Feature Lambda Function         Normal Function (def)
Syntax                 One-liner             Multi-line allowed
Naming                 Anonymous             Named
Usage             Quick, temporary functions             Reusable and readable
Supports Docstring                                      
Used with             map(), filter(), sort(), etc.             Anywhere

๐ŸŽ“ Practice Task for Students

Try writing a lambda function that checks if a number is even or odd:

is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(7))  # Output: Odd

๐Ÿงฉ Real-World Use Case: Sorting Dictionary by Value

data = {'a': 5, 'b': 2, 'c': 9}
sorted_data = sorted(data.items(), key=lambda item: item[1])
print(sorted_data)  # Output: [('b', 2), ('a', 5), ('c', 9)]

✅ Conclusion

Lambda functions are an elegant way to write quick, throwaway functions without creating full function definitions. For students, they help understand functional programming. For professionals, they help write cleaner, faster, and more Pythonic code.

When used wisely, lambda functions can improve your code efficiency — just remember to keep them short and readable!



watch video to understand Python Lambda Function below: 


 

 

Python Functions || learn python programming || Python for Beginners

Python Functions
This video tutorial contains complete explanation from part 1, 2 and 3 of Python Functions.

๐Ÿง  What You'll Learn

This complete video tutorial combines all key concepts from our Python Functions series (Part 1, 2, and 3). It’s perfect for beginners who want to understand functions from scratch and become confident using them in real projects.

  • What functions are and why they are used in Python
  • How to define and call functions
  • Understanding function parameters and return values
  • Default parameters, *args and **kwargs
  • Lambda functions and variable scope

๐Ÿ“ฝ️ Video Walkthrough

This all-in-one video recaps every important topic about Python functions. Whether you're revising or learning for the first time, this session will give you a clear and practical understanding of how functions work in Python, with examples and code demonstrations explained in Hindi.

  • Defining and calling functions using the def keyword
  • Different types of arguments: positional, keyword, default
  • Returning single and multiple values
  • Working with *args and **kwargs
  • Introduction to lambda functions and scope handling

✅ Key Takeaways

  • Functions make your code reusable, organized, and easy to debug.
  • Arguments and return values allow data flow between functions.
  • *args and **kwargs give flexibility to accept variable inputs.
  • Understanding scope and lambda functions is key for writing efficient Python code.

Python Functions - PART -3 || Python tutorial || Python for Beginners ||...

๐Ÿง  What You'll Learn

In Part 3 of our Python Functions tutorial series, we’ll explore advanced concepts that help you write more flexible and powerful functions.

  • Understanding default parameter values
  • Using variable-length arguments (*args and **kwargs)
  • Scope of variables inside and outside functions
  • Introduction to lambda (anonymous) functions

๐Ÿ“ฝ️ Video Walkthrough

This video explains how to enhance your Python functions by adding default parameters, accepting a variable number of arguments, and understanding the scope of variables. You will also get a brief introduction to lambda functions, which provide a compact way to write small anonymous functions.

  • Setting default values for function parameters
  • Using *args for non-keyword variable arguments
  • Using **kwargs for keyword variable arguments
  • Variable scope: local vs global variables
  • Writing simple lambda functions

✅ Key Takeaways

  • Default parameters allow functions to have optional arguments.
  • *args and **kwargs enable flexible argument passing.
  • Understanding variable scope is crucial to avoid bugs.
  • Lambda functions offer concise syntax for small anonymous functions.

Python Function (part-1)|| Python for beginners || Learn Python

๐Ÿง  What You'll Learn

In this first part of the Python Functions series, you will learn the basics of defining and using functions in Python. This tutorial is perfect for beginners who want to understand how functions help organize code, make it reusable, and improve readability.

  • What is a function in Python?
  • How to define a function using def keyword
  • Understanding function arguments and parameters
  • Calling functions and passing data
  • Using return statements to get results

๐Ÿ“ฝ️ Video Walkthrough

The video explains function basics with simple examples and live coding in Python. You’ll see how to write your own functions, how arguments work, and how to return values. This step-by-step demonstration helps you build a strong foundation for using functions effectively in your Python programs.

  • Syntax of Python functions
  • Defining and calling functions
  • Positional and keyword arguments
  • Using return to send back results
  • Practical examples and exercises

✅ Key Takeaways

  • Functions help organize code into reusable blocks.
  • Use def to create a function.
  • Parameters allow functions to accept input data.
  • Return statements send results back to the caller.
  • Understanding functions is essential for writing clean, maintainable Python code.

Python Dictionary Part-3

๐Ÿง  What You'll Learn

In Part 3 of our Python Dictionaries series, we'll dive deeper into advanced dictionary features and practical use cases to help you master dictionary handling in Python.

  • Dictionary comprehension for creating dictionaries efficiently
  • Using setdefault() method
  • Sorting dictionaries by keys or values
  • Working with immutable keys and hashability
  • Common pitfalls and best practices

๐Ÿ“ฝ️ Video Walkthrough

This video tutorial guides you through advanced dictionary operations with clear examples. You'll learn how to use dictionary comprehensions to write concise code, explore the setdefault() method to simplify value insertion, and see techniques for sorting dictionaries. We also discuss why keys must be immutable and share tips to avoid common mistakes.

  • Creating dictionaries using comprehensions
  • Using setdefault() to manage missing keys
  • Sorting dictionaries by keys and values
  • Understanding immutable keys and hashability
  • Best practices and debugging tips

✅ Key Takeaways

  • Dictionary comprehensions offer a clean and efficient way to create dictionaries.
  • setdefault() simplifies inserting default values without extra checks.
  • Sorting dictionaries requires understanding keys and values distinction.
  • Keys must be immutable (like strings, numbers, tuples) to be valid dictionary keys.
  • Following best practices helps avoid bugs and improves code readability.

Featured Post

GROUP BY, HAVING, and Aggregations in SQL Server Explained

Part 9: GROUP BY, HAVING, and Aggregations in SQL Server Microsoft SQL Server Tutorial Series: Beginner to Expert Welcome to Part 9 of...

Popular Posts