Category: Python

  • Python- Module 5 – Python Objects – Step-by-Step Guide for Beginners

    In Python, everything is an object – yes, even numbers, strings, and functions!

    Let’s understand what objects are, how they work, and how you can create your own.


    🔹 Step 1: What is an Object?

    An object is a collection of data (variables) and behaviors (functions/methods). Think of an object as a real-world thing that has:

    • Properties (like name, color, age)
    • Actions (like speak, walk, drive)

    📌 Example: A Car is an object. It has properties like brand, model, color and actions like start(), stop(), drive().


    🔹 Step 2: Objects Are Created from Classes

    A class is like a blueprint. You use it to create objects.

    📦 Class = Design
    🚗 Object = Real item built from that design


    🔹 Step 3: Define a Class in Python

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        def greet(self):
            print(f"Hi, I am {self.name} and I am {self.age} years old.")
    

     Explanation:

    • class Person: → defines a new class called Person
    • __init__() → a special method that runs when an object is created (like a constructor)
    • self → refers to the current object
    • greet() → a method (function inside the class)

     Step 4: Create Objects from the Class

    p1 = Person("Asha", 25)
    p2 = Person("Ravi", 30)
    
    p1.greet()  # Output: Hi, I am Asha and I am 25 years old.
    p2.greet()  # Output: Hi, I am Ravi and I am 30 years old.
    

    Now, p1 and p2 are objects (also called instances) of the class Person.


    🔹 Step 5: Add More Methods

    You can add more functions (called methods) inside the class:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def greet(self):
            print(f"Hi, I am {self.name} and I am {self.age} years old.")
            
        def checkvote(self):
            if(self.age>=18):
                print("Eligible to Vote")
            else:
                print("Not Eligible to Vote")
    
    a1=Person("Asha",10)
    a1.greet()
    a1.checkvote()
    
    
    
    ConceptReal Life Example
    ClassMobile phone design
    ObjectReal phone in your hand
    AttributeBrand, model, price
    MethodCall, message, camera

    Example :

    class student:
        def __init__ (self,rollno,stname,m1,m2,m3,m4,m5):
            self.rollno=rollno
            self.stname=stname
            self.m1=m1
            self.m2=m2
            self.m3=m3
            self.m4=m4
            self.m5=m5
    
        def result(self):
            total=self.m1+self.m2+self.m3+self.m4+self.m5
            print("Total = ",total)
    
        def welcome(self):
            print("Welcome : ",self.stname)
            
    s1=student(1001,'Raja',100,100,80,70,90)
    s2=student(1002,'Kumar',100,100,80,100,90)
    s1.welcome()
    s1.result()
    s2.welcome()
    s2.result()
    

    Output

    Welcome : Raja
    Total = 440
    Welcome : Kumar
    Total = 470

  • Python Module 4: Data Structures in Python – Complete Notes

    🧠 What are Data Structures?

    Data structures are ways to store and organize data so we can access and modify it efficiently.

    🧱 Types of Built-in Data Structures in Python

    Python has 4 main built-in data structures:

    TypeOrderedMutableAllows DuplicatesSyntax
    List✅ Yes✅ Yes✅ Yes[]
    Tuple✅ Yes❌ No✅ Yes()
    Set❌ No✅ Yes❌ No (unique){}
    Dictionary✅ Yes✅ Yes❌ No (unique keys){key: value}

    1️⃣ Lists – Ordered and Mutable

    Used to store multiple items in a single variable.

    🔹 Syntax:

    my_list = [10, 20, 30, "Python", True]
    

    🔹 Operations

    my_list[1]          # Access
    my_list.append(40)  # Add at end
    my_list.remove(20)  # Remove item
    my_list[0] = 100    # Update item
    

    2️⃣ Tuples – Ordered and Immutable

    Like lists, but cannot be changed (read-only).

    🔹 Syntax:

    my_tuple = (10, 20, 30, "Python")
    

    🔹 Operations

    my_tuple[1]        # Access
    len(my_tuple)      # Length
    # Cannot add or remove elements
    

    📌 Use when data should not be changed, like dates or constants.


    3️⃣ Sets – Unordered, No Duplicates

    Used to store unique values.

    🔹 Syntax:

    my_set = {1, 2, 3, 4, 4, 2}
    print(my_set)  # Output: {1, 2, 3, 4}
    

    🔹 Operations

    my_set.add(5)        # Add item
    my_set.remove(3)     # Remove item
    

    ✅ Good for membership tests and removing duplicates.


    4️⃣ Dictionaries – Key-Value Pairs


    Used to store data in pairs (like a real-life dictionary).

    🔹 Syntax:

    my_dict = {"name": "John", "age": 25, "is_student": True}
    

    🔹 Operations

    my_dict["name"]             # Access value
    my_dict["age"] = 26         # Update value
    my_dict["city"] = "Chennai" # Add new pair
    del my_dict["is_student"]   # Delete key
    

    🔁 Looping Through Data Structures

    🔹 List/Tuple:

    for item in my_list:
        print(item)
    

    🔹 Set:

    for item in my_set:
        print(item)
    

    🔹 Dictionary:

    for key, value in my_dict.items():
        print(key, value)
    

    🧪 Example Practice:


    students = ["Arun", "Beena", "Charles"]
    print(students)
    marks = (85, 90, 78)
    print(marks)
    unique_subjects = {"Math", "Science", "Math"}  
    print(unique_subjects)
    profile = {"name": "Kumar", "age": 20}
    print(profile)
    

    📌 Summary for Beginners:

    Data TypeUse for…
    ListStore changing sequences
    TupleStore fixed sequences
    SetStore unique items
    DictionaryStore labeled data (key-value)

    real-life use cases with examples

    ✅ 1. List – When Order & Change Matters

    📌 Real-Life Use Case:

    • Shopping List – You add items, remove items, or change quantities.

    🧪 Python Example:

    shopping_list = ["milk", "eggs", "bread"]
    shopping_list.append("butter")      # Add item
    shopping_list.remove("milk")        # Remove item
    shopping_list[0] = "cheese" 
    # Replace "eggs" with "cheese"
    print(shopping_list)  
    # Output: ['cheese', 'bread', 'butter']
    

    ✅ Use When:

    • You need ordered items.
    • Items can change (mutable).
    • Duplicates are okay.

    ✅ 2. Tuple – When Data Shouldn’t Change

    📌 Real-Life Use Case:

    • Date of Birth, GPS coordinates, or Configuration values – These don’t change.
    date_of_birth = (1995, 12, 15)  # year, month, day
    coordinates = (13.0827, 80.2707)  # Chennai GPS
    
    print("Born in:", date_of_birth[0])
    

    ✅ Use When:

    • You want a fixed collection of values.
    • Memory efficiency is important.
    • Used as dictionary keys (immutable).

    ✅ 3. Set – When You Need Only Unique Items

    📌 Real-Life Use Case:

    • Attendees List – To ensure no one is counted twice.
    • Available tags or unique student IDs.
    attendees = {"Alice", "Bob", "Alice", "David"}
    print(attendees)  # Output: {'Alice', 'Bob', 'David'}
    
    attendees.add("Eve")     # Add new person
    attendees.remove("Bob")  # Remove person
    
    print(attendees)
    

    ✅ Use When:

    • Order doesn’t matter.
    • No duplicates allowed.
    • You want fast membership test (in operator).

    ✅ 4. Dictionary – Store Data with Labels

    📌 Real-Life Use Case:

    • Student Profile, Bank Account Details, Product Catalog
    student = {
        "name": "Karthik",
        "age": 21,
        "marks": 88,
        "college": "ABC University"
    }
    
    # Accessing values
    print(student["name"])   # Karthik
    student["marks"] = 92    # Update marks
    student["city"] = "Chennai"  # Add new key
    print(student)
    

    ✅ Use When:

    • You need to label values (name, age, etc.).
    • Quick lookup based on key.
    • You want structured data.

    💡 Quick Analogy for Remembering:

    Real LifePython Data Structure
    Shopping listList
    Birth certificateTuple
    Guest register bookSet
    Student ID cardDictionary

    🔄 Mixed Example (All in One):

    students = [
        {"name": "Arun", "age": 17, "subjects": {"Math", "Science"}},
        {"name": "Beena", "age": 18, "subjects": {"Math", "English"}},
    ]
    
    for student in students:
        print(f"{student['name']} is {student['age']} years old and studies {student['subjects']}")
    

    This uses:

    • List of students
    • Dictionaries to store each student’s details
    • Sets to store unique subjects

  • Python-Module 3: Control Flow Statements in Python

    🚦 What is Control Flow?

    In real life, we make decisions all the time.
    For example:

    • If it’s raining, take an umbrella.
    • If you finish your homework, then play.

    Python does the same using control flow statements. These help the program decide what to do next.

    1. if Statement

    🧠 Use: To do something only if a condition is true.

    📘 Syntax:

    if condition:
        # do something
    

    🧪 Example:

    if 5 > 2:
        print("5 is greater than 2")
    

    2. if...else Statement

    🧠 Use: To choose between two options.

    📘 Syntax:

    if condition:
        # do this if true
    else:
        # do this if false
    

    🧪 Example:

    age = 16
    if age >= 18:
        print("You can vote")
    else:
        print("You are too young to vote")
    

    3. if…elif…else

    🧠 Use: To check more than two conditions.

    📘 Syntax:

    if condition1:
        # do this
    elif condition2:
        # do this
    else:
        # do this if nothing above is true
    

    🧪 Example:

    score = 85
    if score >= 90:
        print("Grade A")
    elif score >= 80:
        print("Grade B")
    else:
        print("Try harder")
    

    🔁 4. while Loop

    🧠 Use: To repeat as long as the condition is true.

    📘 Syntax:

    while condition:
        # do this again and again
    

    🧪 Example:

    count = 1
    while count <= 3:
        print("Count is", count)
        count += 1
    

    🔁 5. for Loop

    🧠 Use: To loop through a list, string, or range.

    📘 Syntax:

    for item in list:
        # do this for each item
    

    🧪 Example:

    for i in range(1, 4):
        print("Number:", i)
    

    6. break Statement

    🧠 Use: To stop a loop early.

    📘 Syntax:

    for i in range(5):
        if i == 3:
            break
        print(i)
    

    🧪 Output

    0
    1
    2
    

    🔄 7. continue Statement

    🧠 Use: To skip one step and move to the next.

    📘 Syntax:

    for i in range(5):
        if i == 3:
            continue
        print(i)
    

    🧪 Output

    0
    1
    2
    4
    

  • Python Module 2 (Operators and Expressions)

    In this lesson, we will learn about Operators and Expressions in Python.

    ✨ Types of Operators in Python

    1. Arithmetic Operators

    These are used for basic math:

    OperatorDescriptionExample (a = 10, b = 3)Result
    +Additiona + b13
    -Subtractiona - b7
    *Multiplicationa * b30
    /Divisiona / b3.33
    //Floor Divisiona // b3
    %Modulus (remainder)a % b1
    **Exponentiationa ** b1000

    📌 Try this in Python:

    print(5 + 3)
    print(7 % 2)
    print(2 ** 3)
    

    2. Comparison (Relational) Operators

    Compare values and return True or False.

    OperatorDescriptionExample (a = 10, b = 3)Result
    ==Equal toa == bFalse
    !=Not equal toa != bTrue
    >Greater thana > bTrue
    <Less thana < bFalse
    >=Greater than or equala >= bTrue
    <=Less than or equala <= bFalse

    3. Logical Operators

    Used to combine conditional statements.

    OperatorDescriptionExampleResult
    andTrue if both are trueTrue and FalseFalse
    orTrue if at least one is trueTrue or FalseTrue
    notReverses resultnot TrueFalse

    4. Assignment Operators

    Assign values to variables.

    OperatorExampleSame As
    =x = 5Assign 5 to x
    +=x += 3x = x + 3
    -=x -= 2x = x - 2
    *=x *= 4x = x * 4
    /=x /= 2x = x / 2
    //=x //= 2x = x // 2
    %=x %= 2x = x % 2
    **=x **= 3x = x ** 3

    5.Bitwise Operators

    Bitwise operators work on bits (0s and 1s) of integers at the binary level.

    They are used to perform operations like AND, OR, XOR, NOT, etc., bit-by-bit.

    OperatorDescriptionExample
    &AND5 & 3 = 1
    ``OR
    ^XOR5 ^ 3 = 6
    ~NOT~5 = -6
    <<Left Shift5 << 1 = 10
    >>Right Shift5 >> 1 = 2

    🧪 6. Identity and Membership Operators

    Identity :

    x = [1, 2]
    y = x
    print(x is y)  # True
    

    Membership

    fruits = ["apple", "banana"]
    print("apple" in fruits)  # True
    

    Expressions in Python

    x = 10
    y = 5
    result = (x + y) * 2
    print(result) # Output: 30

    Operator Precedence

    Determines the order in which operations are performed.

    From highest to lowest:

    1. () – Parentheses
    2. ** – Exponentiation
    3. +, - (Unary)
    4. *, /, //, %
    5. +, - (Binary)
    6. <, <=, >, >=, ==, !=
    7. and
    8. or
    9. =, +=, -=, etc.

    Example :

    x = 10
    y = 4
    z = 3
    
    result = x + y * z - y / 2
    print(result)
    # Output: 10 + 12 - 2.0 = 20.0
    

    Examples


    🔢 1. Arithmetic Operators

    a = 10
    b = 3
    
    print(a + b)   # Output: 13
    print(a - b)   # Output: 7
    print(a * b)   # Output: 30
    print(a / b)   # Output: 3.333...
    print(a // b)  # Output: 3
    print(a % b)   # Output: 1
    print(a ** b)  # Output: 1000
    

    🤝 2. Comparison Operators

    x = 5
    y = 10
    
    print(x == y)  # Output: False
    print(x != y)  # Output: True
    print(x > y)   # Output: False
    print(x < y)   # Output: True
    print(x >= 5)  # Output: True
    print(y <= 10) # Output: True
    

    🧠 3. Logical Operators

    a = True
    b = False
    
    print(a and b)  # Output: False
    print(a or b)   # Output: True
    print(not a)    # Output: False
    
    

    🧱 4. Bitwise Operators

    a = 5      # 0101
    b = 3      # 0011
    
    print(a & b)  # Output: 1  (0001)
    print(a | b)  # Output: 7  (0111)
    print(a ^ b)  # Output: 6  (0110)
    print(~a)     # Output: -6 (inverts bits)
    print(a << 1) # Output: 10 (shifts left: 1010)
    print(a >> 1) # Output: 2  (shifts right: 0010)
    


    ✍️ 5. Assignment Operators

    x = 5
    x += 3     # Same as x = x + 3
    print(x)   # Output: 8
    
    x *= 2     # x = x * 2
    print(x)   # Output: 16
    
    

    🔍 6. Identity Operators

    a = [1, 2]
    b = a
    c = [1, 2]
    
    print(a is b)  # Output: True
    print(a is c)  # Output: False
    print(a == c)  # Output: True (values are same)
    

    🍎 7. Membership Operators

    fruits = ["apple", "banana", "cherry"]
    
    print("banana" in fruits)   # Output: True
    print("grape" not in fruits)  # Output: True
    

    🎯 8. Expressions Example

    result = (5 + 3) * 2 - 4 / 2
    print(result)  # Output: 14.0
    

    Welcome to the Python Programming Quiz!

    Test your knowledge by selecting the correct answers. You will immediately see if you’re right or wrong.

    Score: 0
  • Python Module 1: Variables and Data Types (with Examples & Output)

    🎯 Learning Objectives

    By the end of this module, students will be able to:

    • Understand what variables are and how to use them.
    • Identify and apply different data types.
    • Perform type conversions (casting).
    • Avoid common variable naming mistakes.

    🧠 1. What is a Variable?

    • A variable is a name that refers to a value stored in memory.
    • Think of it as a label on a box that stores a piece of data.
    name = "Alice"
    age = 20
    

    name holds "Alice", age holds 20.

    🗂️ 2. Python Data Types

    Data TypeExampleDescription
    int25Whole numbers
    float3.14Decimal numbers
    str"Hi"Text values
    boolTrueLogical values (True/False)

    Example:

    x = 10        # int
    y = 3.5       # float
    name = "Sam"  # str
    flag = True   # bool
    

    📝 3. Variable Naming Rules

    Valid Names:

    • Must begin with a letter or _
    • Can contain letters, digits, and underscores
    • Case-sensitive (nameName)

    Example :

    # 2name = "Alex"    ❌ starts with number
    # user-name = "Bob" ❌ contains dash
    # my name = "Joe"   ❌ contains space
    

    🔄 4. Type Conversion (Casting)

    age = "20"          # str
    nextyearage=age+1   
    
    #TypeError: can only concatenate str (not "int") to str
    
    nextyearage=int(age)+1   
    print (nextyearage)      # 21
    

    Use int(), float(), str(), bool() for conversions.

    🧪 5. Checking Data Types

    use type() function

    print(type(10))        # <class 'int'>
    print(type("hello"))   # <class 'str'>
    

    ⚠️ 6. Common Mistakes

    MistakeWhy it’s wrongFix
    "age" + 5Can’t add string and integerConvert first: int("age") + 5
    user name = "Tom"Variable names can’t have spacesUse underscore: user_name

    🧩 7. Practice Time (Live Demo)

    1. Create a variable city and assign your city name.
    2. Create variables for your birth year and calculate your age.
    3. Convert a float to a string and print the result and type.
    4. Check if bool(0) and bool("Hi") return True or False.

    📚 Quick Recap

    • Variables hold data values.
    • Data types define the kind of value.
    • Use type() to inspect types.
    • Convert types using casting functions like int(), str().
    • Follow naming rules for valid variables.

    Example 1:

    name = "John"
    age = 28
    height = 5.9
    
    print(name)
    print(age)
    print(height)
    
    Output

    John
    28
    5.9
    


    Example 2: Check Data Type

    print(type(name))   # str
    print(type(age))    # int
    print(type(height)) # float
    
    Output

    <class 'str'>
    <class 'int'>
    <class 'float'>
    


    Example 3: Type Casting

    age = 28
    height = 5.9
    
    age = float(age)
    height = str(height)
    
    print(age)
    print(type(age))
    print(height)
    print(type(height))
    
    Output

    28.0
    <class 'float'>
    5.9
    <class 'str'>
    

    Example 4: Assign multiple values in one line.

    a, b, c = 1, 2, 3
    print(a, b, c)
    
    Output

    1 2 3
    


    Example 5: Assign Same Value to Multiple Variables

    x = y = z = "Python"
    print(x, y, z)
    
    Output

    Python Python Python
    


    Example 6: String Concatenation using Variables

    first = "Hello"
    last = "World"
    message = first + " " + last
    print(message)
    
    Output

    Hello World
    


    Example 7: Numeric Calculation Using Variables

    price = 50
    quantity = 3
    total = price * quantity
    print("Total:", total)
    
    Output

    Total: 150
    


    Example 8: Boolean Example

    is_logged_in = True
    print("Login status:", is_logged_in)
    
    Output

    Login status: True
    


    Example 9: Dynamic Typing in Python

    var = 10
    print(type(var))  # int
    
    var = "Ten"
    print(type(var))  # str
    
    Output

    <class 'int'>
    <class 'str'>
    


    Example 10: Input and Type Conversion

    name = input("Enter your name: ")
    age = int(input("Enter your age: "))
    print(f"Hello {name}, you are {age} years old.")
    
    Output

    Enter your name: Alex
    Enter your age: 21
    
    Hello Alex, you are 21 years old.
    


    Example 11: Using type() in Debugging

    value = "123"
    print(value + " is a string")      # works
    # print(value + 5)                 # ❌ TypeError
    
    value = int(value)
    print(value + 5)                   # ✅ Now works
    
    Output

    123 is a string
    128
    


    Example 12: Calculate the Area of a Rectangle

    length = 10
    width = 5
    area = length * width
    print("Area of rectangle:", area)
    
    Output

    Area of rectangle: 50
    


    Example 13: Store and Display Product Info

    product_name = "Laptop"
    price = 799.99
    in_stock = True
    
    print("Product:", product_name)
    print("Price: $", price)
    print("Available:", in_stock)
    
    Output

    Product: Laptop
    Price: $ 799.99
    Available: True
    


    Example 14: Temperature Storage in Celsius and Fahrenheit

    celsius = 25
    fahrenheit = (celsius * 9/5) + 32
    
    print("Celsius:", celsius)
    print("Fahrenheit:", fahrenheit)
    
    Output

    Celsius: 25
    Fahrenheit: 77.0
    


    Example 15: Using Variables to Format Strings

    name = "Sara"
    score = 95
    
    print(f"{name} scored {score} points.")
    
    Output

    Sara scored 95 points.
    


    Example 16: Variable Reassignment

    x = 10
    print("Before:", x)
    
    x = 20
    print("After:", x)
    
    Output

    Before: 10
    After: 20
    


    Example 17: Using bool() Function

    print(bool(0))      # False
    print(bool(123))    # True
    print(bool(""))     # False
    print(bool("Hi"))   # True
    
    Output

    False
    True
    False
    True
    


    Example 18: Type Conversion with Errors (Demonstration)

    x = "ten"
    # y = int(x)  # This will cause an error
    
    print("Cannot convert non-numeric string to integer")
    
    Output

    Cannot convert non-numeric string to integer
    


    Example 19: Combining Strings and Numbers with Casting

    name = "Liam"
    score = 88
    
    print(name + " scored " + str(score) + " marks.")
    
    Output

    Liam scored 88 marks.
    


    Example 20: Constants (Using UPPERCASE by Convention)

    PI = 3.14159
    radius = 7
    area = PI * radius * radius
    
    print("Circle Area:", round(area, 2))
    
    Output

    Circle Area: 153.94
    

    Welcome to the Python Programming Quiz!

    Test your knowledge by selecting the correct answers. You will immediately see if you’re right or wrong.

    Score: 0