Author: Saravana Kumar

  • What is __init__.py in Python?

    🧩 What is __init__.py in Python?


    πŸ“˜ Definition

    • __init__.py is a special Python file used to mark a folder as a Python package.
    • It tells Python: “This folder contains Python code you can import.

    πŸ“¦ Where is it used?

    It is placed inside a package folder like this:

    mypackage/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ add.py
    β”œβ”€β”€ sub.py
    
    

    βœ… Why __init__.py is Important

    PurposeExplanation
    Marks folder as a packageWithout it, Python may not treat the folder as a package.
    Runs code when importedYou can put code in it that runs automatically.
    Helps in organizing importsMakes it easy to control what’s imported.

    βœ… Example 1: Simple Empty __init__.py

    # __init__.py
    # (can be empty)
    
    

    Usage:

    from mypackage import add
    print(add.add(2, 3))  # Output: 5
    
    

    βœ… Example 2: With Code in __init__.py

    # __init__.py
    print("Welcome to mypackage!")
    
    def greet():
        print("Hello from the package!")
    
    

    Usage:

    import mypackage
    
    mypackage.greet()
    
    

    πŸ–¨ Output:

    Welcome to mypackage!
    Hello from the package!
    
    

    βœ… Example 3: Control Imports

    If you want only certain modules to be accessible:

    # __init__.py
    __all__ = ['add']
    
    

    Now:

    from mypackage import *
    # Only add is available, not sub
    
    

    πŸ” Summary

    ItemMeaning
    __init__.pyMakes folder a package
    Can be emptyYes
    Can have codeYes (runs on import)
    Can control what to importYes with __all__

    πŸ“ Practice Task

    ❓ Create a package with:

    • __init__.py (prints “Package loaded”)
    • calc.py (function to add numbers)
    • Then import and use it.

    βœ… Answer:

    Folder: tools/

    ➑️ __init__.py

    print("Package loaded!")
    
    

    ➑️ calc.py

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

    ➑️ Main file:

    from tools import calc
    print(calc.add(4, 5))  # Output: 9
    
    

  • Library and Packages in Python -Introduction

    Here’s a simple explanation of Libraries and Packages in Python β€” with examples, usage, and practice questions


    πŸ“š What is a Library in Python?

    • A library is a collection of useful code (functions, classes, modules).
    • It helps you do things quickly, without writing code from scratch.
    • Python has many libraries for math, data, web, AI, etc.

    πŸ”Ή Examples of Libraries:

    LibraryUse Case
    mathMathematics (sqrt, sin)
    randomRandom numbers
    datetimeDates and time
    osOperating system tasks
    numpyNumbers, arrays
    pandasData analysis
    matplotlibDrawing graphs/plots
    requestsWeb API calls

    πŸ“¦ What is a Package?

    • A package is a folder that contains modules (Python files) and a special file called __init__.py.
    • Packages help to organize libraries better.
    • You can think of:
      • Library = a toolset
      • Package = toolbox with organized tools (modules)

    βœ… Example: Using a Library

    1. Math Library:

    import math
    print(math.pi)         # 3.1415...
    print(math.sqrt(25))   # 5.0
    
    

    2. Random Library:

    import random
    print(random.randint(1, 10))  # Random number between 1 and 10
    
    

    βœ… Using an External Library

    • Some libraries are not built-in. You need to install them using pip:
    pip install pandas
    
    

    Then use it:

    import pandas as pd
    data = pd.Series([1, 2, 3])
    print(data)
    
    

    βœ… Example: Package Structure

    Imagine this folder:

    mypackage/
        __init__.py
        add.py
        sub.py
    
    

    add.py

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

    sub.py

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

    Use the Package:

    from mypackage import add, sub
    print(add.add(3, 2))
    print(sub.sub(5, 2))
    
    

    πŸ“ Practice Questions + Answers


    ❓ Q1: What is the difference between a module and a library?

    βœ… Answer:

    • A module is one Python file (.py) with code.
    • A library is a collection of modules.
    • A package is a folder containing modules.

    ❓ Q2: Use the random library to generate a number between 100 and 200.

    βœ… Code:

    import random
    print(random.randint(100, 200))
    
    

    ❓ Q3: Install and use the numpy library to create a number array.

    βœ… Code:

    pip install numpy
    
    

    βœ… Python:

    import numpy as np
    arr = np.array([10, 20, 30])
    print(arr)
    
    

    ❓ Q4: What is the role of __init__.py in a package?

    βœ… Answer:

    • It tells Python that the folder is a package.
    • It can be empty or contain startup code.

    ❓ Q5: Create your own library with a function to find the square of a number.

    βœ… Create mylib.py:

    def square(n):
        return n * n
    
    

    βœ… Use it:

    import mylib
    print(mylib.square(6))  # Output: 36
    
    

    πŸ”„ Summary Table

    TermMeaning
    ModuleSingle .py file
    LibraryCollection of modules (ready-to-use code)
    PackageFolder of modules with __init__.py
    pipPython package installer

  • Modules in Python

    Here’s a simple explanation of Modules in Python with examples, definitions, and practice questions


    🧠 What is a Module in Python?

    • A module is a Python file (.py) that contains code, functions, or variables.
    • You can import and use it in another file.
    • Python has built-in modules and you can also create your own.

    πŸ” Why Use Modules?

    • To reuse code.
    • To organize code in separate files.
    • To keep programs clean and simple.

    βœ… Types of Modules

    TypeExample
    Built-inmath, random, datetime
    User-definedYour own file like myfile.py
    External (3rd party)numpy, pandas (need to install)

    βœ… Importing a Module

    πŸ‘‰ Syntax:

    import module_name
    
    

    πŸ”Ή Example:

    import math
    print(math.sqrt(16))  # Output: 4.0
    
    

    βœ… Using Specific Functions from a Module

    from math import sqrt, pi
    print(sqrt(25))       # Output: 5.0
    print(pi)             # Output: 3.1415926535...
    
    

    βœ… Rename a Module (alias)

    import math as m
    print(m.pow(2, 3))  # Output: 8.0
    
    

    βœ… Creating Your Own Module

    Step 1: Create a file called mymodule.py

    # mymodule.py
    def greet(name):
        print("Hello", name)
    
    def add(a, b):
        return a + b
    
    

    Step 2: Use it in another file:

    # main.py
    import mymodule
    
    mymodule.greet("Ravi")
    print(mymodule.add(5, 3))  # Output: 8
    
    

    βœ… Built-in Module Examples

    πŸ”Ή math Module

    import math
    print(math.ceil(4.2))    # Output: 5
    print(math.floor(4.7))   # Output: 4
    print(math.factorial(5)) # Output: 120
    
    

    πŸ”Ή random Module

    import random
    print(random.randint(1, 10))  # Random number from 1 to 10
    
    

    πŸ”Ή datetime Module

    import datetime
    now = datetime.datetime.now()
    print(now)  # Current date and time
    
    

    πŸ“ Practice Questions + Answers


    ❓ Q1: Import math module and print the square root of 81.

    βœ… Answer:

    import math
    print(math.sqrt(81))  # Output: 9.0
    
    

    ❓ Q2: Create your own module with a function that says “Welcome!” and call it.

    βœ… Answer:

    File: mygreet.py

    def welcome():
        print("Welcome to Python!")
    
    

    File: main.py

    import mygreet
    mygreet.welcome()
    
    

    ❓ Q3: Use the random module to print a random number between 50 and 100.

    βœ… Answer:

    import random
    print(random.randint(50, 100))
    
    

    ❓ Q4: From math module, import only pow and sqrt.

    βœ… Answer:

    from math import pow, sqrt
    print(pow(2, 3))    # 8.0
    print(sqrt(49))     # 7.0
    
    

    ❓ Q5: What is the benefit of using modules?

    βœ… Simple Answer:

    • Reuse code
    • Organize code
    • Avoid writing the same code again

    πŸ“Œ Summary Table

    ConceptExample
    importimport math
    fromfrom math import sqrt
    asimport math as m
    User Moduleimport mymodule
    External ModuleInstall with pip install

  • Functions in Python

    Here’s a simple explanation of functions in Python in easy international English, perfect for students and beginners:


    🧠 What is a Function?

    • A function is a block of code that does a specific job.
    • You can use it again and again.
    • It helps make your program clean and easy.

    πŸ”§ Why Use Functions?

    • Avoid writing the same code again.
    • Break big problems into small parts.
    • Makes your program organized.

    ✏️ How to Create a Function

    βœ… Syntax:

    def function_name():
        # your code here
    
    

    βœ… Example:

    def say_hello():
        print("Hello, students!")
    
    

    ▢️ How to Call a Function

    say_hello()
    
    

    βœ… Function with Parameters

    • You can send values into a function using parameters.
    def greet(name):
        print("Hello", name)
    
    

    Call it like:

    greet("Alice")
    greet("Ravi")
    
    

    βœ… Function with Return Value

    • A function can give back (return) a value.
    def add(a, b):
        return a + b
    
    result = add(5, 3)
    print("Sum is:", result)
    
    

    🧊 Types of Functions in Python

    TypeExample Code
    No parameters, no returndef greet(): print("Hi")
    With parametersdef greet(name): print(name)
    Return somethingdef add(a, b): return a + b
    Built-in functionsprint(), len(), type()

    πŸ›  Activity – Create and Use a Function

    def multiply(x, y):
        result = x * y
        return result
    
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    print("Multiplication is:", multiply(num1, num2))
    
    

    βœ… Summary Table

    TermMeaning
    defKeyword to define a function
    ParameterInput to function (inside brackets)
    ReturnOutput from the function
    CallRun the function using its name

    Here are more examples, practice questions, and answers to help students understand Functions in Python better


    βœ… More Function Examples


    πŸ”Ή Example 1: Function with No Parameters, No Return

    def welcome():
        print("Welcome to Python class!")
    
    welcome()
    
    

    πŸ”Ή Example 2: Function with Parameters

    def greet(name):
        print("Hello", name)
    
    greet("Asha")
    greet("John")
    
    

    πŸ”Ή Example 3: Function with Return

    def square(n):
        return n * n
    
    result = square(4)
    print("Square is:", result)
    
    

    πŸ”Ή Example 4: Find Maximum of Two Numbers

    def find_max(a, b):
        if a > b:
            return a
        else:
            return b
    
    print("Max is:", find_max(10, 20))
    
    

    πŸ”Ή Example 5: Even or Odd

    def check_even_odd(n):
        if n % 2 == 0:
            return "Even"
        else:
            return "Odd"
    
    print(check_even_odd(7))  # Output: Odd
    
    

    πŸ”Ή Example 6: Factorial of a Number

    def factorial(n):
        result = 1
        for i in range(1, n+1):
            result *= i
        return result
    
    print("Factorial of 5 is:", factorial(5))  # 120
    
    

    πŸ”Ή Example 7: Sum of a List

    def sum_list(numbers):
        total = 0
        for n in numbers:
            total += n
        return total
    
    print(sum_list([1, 2, 3, 4]))  # Output: 10
    
    

    πŸ“ Practice Questions + Answers


    ❓ Q1: Write a function that multiplies two numbers and returns the result.

    βœ… Answer:

    def multiply(a, b):
        return a * b
    
    print(multiply(3, 4))  # Output: 12
    
    

    ❓ Q2: Create a function that checks if a number is positive or negative.

    βœ… Answer:

    def check_number(n):
        if n >= 0:
            return "Positive"
        else:
            return "Negative"
    
    print(check_number(-5))  # Output: Negative
    
    

    ❓ Q3: Write a function that returns the length of a word.

    βœ… Answer:

    def word_length(word):
        return len(word)
    
    print(word_length("Python"))  # Output: 6
    
    

    ❓ Q4: Write a function that returns the reverse of a string.

    βœ… Answer:

    def reverse_string(text):
        return text[::-1]
    
    print(reverse_string("hello"))  # Output: olleh
    
    

    ❓ Q5: Write a function that returns the average of 3 numbers.

    βœ… Answer:

    def average(a, b, c):
        return (a + b + c) / 3
    
    print(average(10, 20, 30))  # Output: 20.0
    
    

    πŸ“š Challenge Practice

    ❓ Q6: Create a function that takes a list of numbers and returns only even numbers.

    βœ… Answer:

    def get_even_numbers(numbers):
        evens = []
        for n in numbers:
            if n % 2 == 0:
                evens.append(n)
        return evens
    
    print(get_even_numbers([1, 2, 3, 4, 5, 6]))  # Output: [2, 4, 6]
    
    

    ❓ Q7: Write a function that counts vowels in a string.

    βœ… Answer:

    def count_vowels(text):
        vowels = 'aeiouAEIOU'
        count = 0
        for char in text:
            if char in vowels:
                count += 1
        return count
    
    print(count_vowels("Python is easy"))  # Output: 4
    
    

    βœ… Summary

    TypeExample
    No parameters, no returndef greet(): print("Hi")
    With parametersdef add(a, b): print(a + b)
    Return valuedef square(x): return x * x
    Real-world useChecking even/odd, sum, max, etc.

  • Exception Handling in Python

    🧠 What is an Exception?

    • Sometimes, a program has an error while running.
    • These errors are called exceptions.
    • Example: Dividing a number by zero β†’ this gives an error.

    πŸ§ͺ Example:

    print(10 / 0)
    

    πŸ‘† This gives an error: ZeroDivisionError


    🎯 Why Use Exception Handling?

    • To stop the program from crashing when error happens.
    • We can show a friendly message instead.

    πŸ“˜ Keywords Used:

    KeywordMeaning (Simple)
    tryWrite risky code here
    exceptWhat to do if error happens
    elseWhat to do if no error happens
    finallyAlways do this, error or no error
    raiseYou make your own error

    πŸ›  Structure:

    try:
        # Your code
    except:
        # If error happens
    else:
        # If no error happens
    finally:
        # Always run this
    

    πŸ“Œ Real-Life Example:

    • ATM machine:
      • If you enter the wrong PIN β†’ show error, don’t crash!
    • Same in Python: If something goes wrong, show a message, not crash.

    Examples :

    1) Demo crash without handling:

    num = int(input("Enter a number: "))
    print(100 / num)
    

    2) Using try-except

    try:
        num = int(input("Enter a number: "))
        print(100 / num)
    except ZeroDivisionError:
        print("You cannot divide by zero!")
    except ValueError:
        print("Please enter a valid number.")
    

    3) else and finally

    try:
        num = int(input("Enter a number: "))
        result = 100 / num
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    else:
        print("Result is:", result)
    finally:
        print("Execution complete.")
    

    4) Handling Multiple Errors

    try:
        lst = [1, 2, 3]
        index = int(input("Enter index: "))
        print(lst[index])
    except (IndexError, ValueError) as e:
        print("Error:", e)
    

    5) Custom Exceptions

    age = int(input("Enter your age: "))
    if age < 18:
        raise Exception("You must be at least 18 years old.")
    

    6) Creating Your Own Exception Class

    class UnderAgeError(Exception):
        pass
    
    age = int(input("Enter age: "))
    if age < 18:
        raise UnderAgeError("You are under 18, not allowed!")
    

    7) Get two inputs and safely divide them.

    try:
        a = int(input("Enter numerator: "))
        b = int(input("Enter denominator: "))
        result = a / b
        print("Result:", result)
    except ZeroDivisionError:
        print("Denominator cannot be zero!")
    except ValueError:
        print("Please enter valid numbers.")
    

    8)Ask for an index and print item from a list.

    fruits = ["apple", "banana", "cherry"]
    try:
        i = int(input("Enter index (0–2): "))
        print("Fruit:", fruits[i])
    except IndexError:
        print("Index out of range.")
    except ValueError:
        print("Invalid input. Please enter a number.")
    

    9) Raise exception if password is less than 6 characters.

    try:
        username = input("Username: ")
        password = input("Password: ")
        if len(password) < 6:
            raise ValueError("Password too short! Must be at least 6 characters.")
        print("Login successful.")
    except ValueError as ve:
        print("Error:", ve)
    

    10) Age Verifier using Custom Exception

    class AgeTooLowError(Exception):
        pass
    
    try:
        age = int(input("Enter your age: "))
        if age < 18:
            raise AgeTooLowError("Access denied: You are under 18.")
        else:
            print("Access granted.")
    except AgeTooLowError as e:
        print(e)
    except ValueError:
        print("Please enter a valid number.")
    

    11) Read a file. If not found, handle error.

    try:
        with open("data.txt", "r") as file:
            content = file.read()
            print(content)
    except FileNotFoundError:
        print("File not found.")