Showing posts with label Python Tutorial. Show all posts
Showing posts with label Python Tutorial. 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!


Python Modules Made Easy: A Beginner to Pro Guide with Examples

← Back to Home

 

🐍 Python Modules: A Simple Guide for Beginners and Professionals

In Python, modules help you organize code, reuse functionality, and keep things clean and manageable. Whether you're a student just starting out or a developer building real-world applications, understanding modules is essential.


πŸ“¦ What is a Python Module?

A module is a file containing Python code — it can include functions, variables, and classes. By importing modules, you can access their functionality in your own programs.

Think of a module as a toolbox: instead of building tools from scratch every time, you just bring the right toolbox and use what’s inside.


πŸ”— Built-in Modules

Python comes with many built-in modules like math, random, and datetime.

✏️ Example: Using the math module

import math

print(math.sqrt(16))     # 4.0
print(math.pi)           # 3.141592653589793

πŸ“ Creating Your Own Module

You can create your own module by saving Python code in a .py file.

✏️ Step 1: Create a File mytools.py

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

def square(x):
    return x * x

✏️ Step 2: Import and Use It

import mytools

print(mytools.greet("Alice"))   # Hello, Alice!
print(mytools.square(5))        # 25

✅ Now you're using your own module like a pro!


πŸ“š Importing Modules in Different Ways

πŸ”Ή import module

import math
print(math.ceil(2.3))

πŸ”Ή from module import function

from math import sqrt
print(sqrt(16))

πŸ”Ή import module as alias

import random as r
print(r.randint(1, 10))

πŸ“¦ Using External Modules (Installing with pip)

Python has thousands of third-party modules you can install using pip.

✏️ Example: Using requests (HTTP library)

pip install requests
import requests

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

🧠 Why Use Modules?

  • 🧩 Organize code into logical files

  • πŸ” Reuse code in multiple programs

  • πŸ‘¨‍πŸ‘©‍πŸ‘§ Collaborate in teams more easily

  • πŸ“¦ Use powerful libraries from the community


⚠️ Best Practices

Do ✅ Don’t ❌
Use clear module names Avoid overly generic names
Group related functions Don’t mix unrelated code
Document your module Don’t leave magic code unexplained
Keep modules small & focused Avoid massive all-in-one files

🧾 Summary

Feature Description
Module Definition         A file with Python code (.py)
Built-in Modules      math, random, datetime, etc.
Custom Modules         Your own reusable .py files
External Modules         Installed via pip (e.g. requests)
Import Syntax Options     import, from, as

🎯 Final Thoughts

Python modules are the building blocks of maintainable and scalable code. As you advance in Python, using and creating modules will become second nature — and a major boost to your coding productivity.


← Back to Home

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.


Dictionaries in Python

← Back to Home

Python Dictionaries:



Dictionaries are python data structures which store the data in key-value pairs. These are like Maps in other similar programming languages.

Dictionaries are not ordered unlike strings, Lists and Tuples.

Keys uniquely define the items in a python dictionary. So duplicate keys are not allowed.

Keys are unique but values are not.

Keys must be of immutable types like strings, numbers and tuples.

Dictionary can contain any type of values.



Creating a Dictionary :

Each key is separated from its value by a colon(:)

The items are separated by commas

All the above paired items are enclosed in curly braces.


watch video below to demonstrate python dictionaries: 





Empty Dictionary:
       An empty dictionary without any item is created with just two curly braces.{}

Example:

              

Dictionary containing items: (create and display)




Accessing values from Dictionary:

Values can be accessed  using square brackets along with the key to obtain its value.

Example:



Both the print commands produces the corresponding values with keys "Name" and "Age".

If we attempt to access the data item which is not present in dictionary, we'll get error as





Updating Dictionary :

Dictionary can be updated by adding a new entry or a Key-Value pair, modifying an existing entry or deleting an existing entry :
Example:

In the above code the key 'Age' has the updated value from 25 to 16.
Also, there is a new entry where key is 'Department' with the value 'Finance'.(see Highlighted)


Deleting Dictionary Element

You can delete either an individual item or entire content of a dictionary.

Entire dictionary can also be deleted in a single operation.

Example 1:


If we now want to print the items, An exception is raised because after the command del dict, dictionary does not  exist.

Example 2:




 Properties of Dictionary Keys:

1. More than one entry per key is not allowed i.e duplicate keys are not allowed. When duplicate keys are assigned, only the last assigned (latest) key exists.

2. Keys must be immutable. i.e you can use strings, numbers and Tuples as dictionary keys . others are not allowed.



Built-in Dictionary functions:

1.  cmp : compares elements of both dict.

             cmp ( dict1 , dict2)

2.   len: Gives total length or the total number of elements in the dictionary.

             len(dict)

3.   str: produces a printable string representation of a dictionary.

            str(dict)

4.  type (variable) - returns the type of passed variable . If passed variable is dictionary, then it returns dictionary type.



Dictionary Methods:

Python uses following dictionary methods:

1.    dict.clear( )

2.    dict.copy( )

3.    dict.fromkeys( )

4.    dict.get(key, default = None)

5.    dict.has_key(key)

6.    dict.items( )

7.    dict.keys()

8.    dict.setdefault(key, default=None)

9.    dict.update(dict2)

10.  dict.values()


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