Showing posts with label Python beginner tutorial. Show all posts
Showing posts with label Python beginner tutorial. Show all posts

Monday, March 16, 2026

Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

March 16, 2026 0



Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

Introduction

Welcome to Lesson 9!
In this lesson, we will learn Object-Oriented Programming (OOP) in Python, which is a powerful way to structure code using classes and objects. OOP helps you write reusable, organized, and maintainable programs.


1. What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities.
Key concepts:

  • Class → Blueprint of an object
  • Object → Instance of a class
  • Attributes → Properties of an object
  • Methods → Functions of an object

2. Creating a Class and Object

Example:

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

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

# Creating an object
person1 = Person("Alice", 20)
person1.greet()  # Output: Hello, my name is Alice and I am 20 years old.

Explanation:

  • __init__ → Constructor method, runs automatically when object is created
  • self → Refers to the current object

3. Inheritance

Inheritance allows a class to reuse code from another class.

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def show_id(self):
        print(f"My student ID is {self.student_id}")

student1 = Student("Bob", 18, "S123")
student1.greet()      # Inherited method
student1.show_id()    # Own method

Benefits:

  • Reuse existing code
  • Create hierarchical relationships
  • Simplify complex programs

4. Encapsulation

Encapsulation is the concept of hiding private details of an object.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

Note: Prefix __ to make an attribute private.


5. Polymorphism

Polymorphism allows methods with the same name to behave differently depending on the object.

class Dog:
    def speak(self):
        print("Woof!")

class Cat:
    def speak(self):
        print("Meow!")

animals = [Dog(), Cat()]
for animal in animals:
    animal.speak()
# Output: Woof! Meow!

6. Practice Exercises

  1. Create a class Car with attributes brand and year, and method display_info().
  2. Create a subclass ElectricCar that inherits from Car and adds battery_capacity.
  3. Create objects of both classes and call their methods.
  4. Make a class Account with private balance and methods deposit and withdraw.


Lesson 8: File Handling and Exception Handling | Coding Class Series

March 16, 2026 0



Lesson 8: File Handling and Exception Handling | Coding Class Series

Introduction

Welcome to Lesson 8!
In this lesson, we will learn about file handling in Python and how to manage errors using exception handling. These skills are essential to make your programs robust and data-driven.


1. File Handling

File handling allows your program to read from and write to files on your computer.

Opening a file:

file = open("example.txt", "w")  # 'w' mode to write
file.write("Hello, Python!")
file.close()

Reading a file:

file = open("example.txt", "r")  # 'r' mode to read
content = file.read()
print(content)  # Output: Hello, Python!
file.close()

Using with statement (recommended):

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

File Modes:

  • r → read
  • w → write (overwrite)
  • a → append
  • rb / wb → read/write binary

2. Exception Handling

Exceptions occur when your program runs into an error.
Python allows you to handle exceptions gracefully using try, except, finally blocks.

Example:

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Enter a number.")
finally:
    print("Execution completed.")

Key Points:

  • try: Block where error might occur
  • except: Handles specific errors
  • finally: Executes always, even if an error occurs

3. Combining File Handling and Exceptions

You can handle file errors with exception handling:

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file name!")

Benefits:

  • Prevents program crashes
  • Provides useful error messages
  • Improves program reliability

4. Practice Exercises

  1. Create a file notes.txt and write 5 lines of text in it.
  2. Read the file and count the number of words.
  3. Write a program that asks the user for a filename and prints its content. Handle errors if the file does not exist.
  4. Create a program that divides two numbers and handles division by zero and invalid input using exception handling.


Lesson 5: Conditional Statements and Loops | Coding Class Series

March 16, 2026 0



Lesson 5: Conditional Statements and Loops | Coding Class Series

Introduction

Welcome to Lesson 5!
In this lesson, we will learn how to make decisions in your code using conditional statements (if, elif, else) and how to repeat tasks efficiently using loops (for and while).


Conditional Statements

Conditional statements let your program execute code based on certain conditions.

Syntax in Python:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

Explanation:

  • if age >= 18: → checks if the condition is True
  • else: → executes if the condition is False

Example with multiple conditions:

marks = 75

if marks >= 90:
    print("Grade: A")
elif marks >= 75:
    print("Grade: B")
else:
    print("Grade: C")

Loops

Loops allow repeating code multiple times without rewriting it.

For Loop

Used to iterate over sequences like lists, strings, or ranges.

for i in range(1, 6):
    print(f"Number: {i}")

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

While Loop

Executes code as long as a condition is True.

count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Practice Exercises

  1. Write a program to check if a number is positive, negative, or zero using if-elif-else.
  2. Print all even numbers from 1 to 50 using a for loop.
  3. Use a while loop to print the first 10 Fibonacci numbers.
  4. Write a program to count the number of vowels in a string using a loop.


क्या मैं Lesson 6 भी बना दूँ?