Introduction to Python

Python is a powerful and easy-to-learn programming language used for web development, automation, data science, artificial intelligence, and more.

It is beginner-friendly and widely used by professionals to build real-world applications.

Why Learn Python?

Feature Description
Easy Syntax Simple and readable like English
Versatile Used in web, AI, automation, apps
High Demand Popular in jobs and freelancing
Large Community Lots of tutorials and support available

Steps to Run Your First Python Program

Step Action
1 Install Python on your system
2 Open code editor (VS Code)
3 Create a new file hello.py
4 Write and run the program

Example


print("Hello, World!")
    

Where Python is Used

  • Web Development
  • Automation & Scripting
  • Game Development
  • Data Science & AI
  • Desktop Applications

Important Concepts

  • Python is an interpreted language
  • No need to compile code
  • Indentation is important

Tips

  • Practice daily
  • Start with small programs
  • Focus on logic building

Common Mistakes

  • Ignoring indentation ❌
  • Copy-paste without understanding ❌
  • Not practicing enough ❌

Install Python & Setup

To start programming in Python, you first need to install it on your computer and set up a proper development environment.

This section will guide you step-by-step to install Python and configure your system correctly.

System Requirements

Requirement Description
Operating System Windows / macOS / Linux
RAM Minimum 4 GB
Storage At least 500 MB free space
Internet Required for download and setup

Steps to Install Python

Step Action
1 Go to official Python website
2 Download latest version
3 Run installer
4 Check "Add Python to PATH"
5 Click Install Now

Verify Installation

After installation, check if Python is installed correctly:


python --version
    

If installed properly, it will display the Python version.

Install Code Editor (VS Code)

Step Action
1 Download VS Code
2 Install the software
3 Open VS Code
4 Install Python extension

Steps to Run Python in VS Code

Step Action
1 Open VS Code
2 Create new file main.py
3 Write Python code
4 Click Run ▶️ button

Example


print("Python is installed successfully!")
    

Important Concepts

  • PATH allows Python to run from any folder
  • .py files are Python program files
  • Interpreter runs Python code line by line

Tips

  • Always install latest Python version
  • Use VS Code for better experience
  • Keep your setup clean and organized

Common Mistakes

  • Not adding Python to PATH ❌
  • Installing wrong version ❌
  • Forgetting to install extension in VS Code ❌

First Python Program

Writing your first program is the beginning of your journey in Python. It helps you understand how code works and how output is displayed.

The most common first program is the Hello World program.

Basic Syntax of Python Program

Concept Description
print() Used to display output on screen
Quotes Text must be inside " " or ' '
Case Sensitivity Python is case-sensitive (Print ≠ print)

Steps to Write First Program

Step Action
1 Open VS Code
2 Create a new file hello.py
3 Write Python code
4 Run the program

Example


print("Hello, World!")
    

Output


Hello, World!
    

More Examples


print("Welcome to Python")
print("My name is Mohit")
print(10 + 5)
    

When to Use print()

  • Displaying messages to user
  • Showing output of calculations
  • Debugging code

Important Concepts

  • Python executes code line by line
  • Each print() statement runs separately
  • No semicolon required at end

Tips

  • Always use correct spelling: print
  • Use quotes for text
  • Run code frequently to test

Common Mistakes

  • Using Print instead of print ❌
  • Forgetting quotes ❌
  • Missing parentheses ❌

🎯 Practice Task

  • Write a program to print your name
  • Print your school or college name
  • Print any number calculation (e.g., 20 + 30)
  • Try printing 3 lines of text

Python Syntax

Python Syntax refers to the set of rules that define how Python programs are written and executed. It is simple, clean, and easy to understand compared to other programming languages.

Learning syntax is important because even a small mistake can cause errors in your program.

Basic Syntax Rules

Rule Description
Indentation Spaces are used to define blocks of code
Case Sensitive Variables and keywords are case-sensitive
No Semicolon No need to end lines with ;
Statements Each line is a statement executed by Python

Indentation Example


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

Indentation is mandatory in Python. Without proper indentation, code will give an error.

Case Sensitivity Example


name = "Mohit"
Name = "Kumar"

print(name)
print(Name)
    

Multiple Statements


print("Hello")
print("Welcome to Python")
print("Learning Syntax")
    

Comments in Python

Comments are used to explain code and are ignored during execution.


# This is a single-line comment

print("Hello")  # This is an inline comment
    

When to Follow Syntax Rules

  • Writing any Python program
  • Using conditions and loops
  • Defining functions
  • Working with classes

Important Concepts

  • Indentation replaces curly braces { }
  • Each block must have same indentation
  • Python code is easy to read due to clean syntax

Tips

  • Use 4 spaces for indentation
  • Keep code clean and readable
  • Use comments to explain logic

Common Mistakes

  • Wrong indentation ❌
  • Mixing tabs and spaces ❌
  • Using wrong case in variables ❌

🎯 Practice Task

  • Write an if statement with correct indentation
  • Create 2 variables with different cases
  • Add comments in your program
  • Run code and fix syntax errors

Variables in Python

A variable is used to store data in a program. It acts like a container that holds values such as numbers, text, or other data.

In Python, you do not need to declare the type of a variable. It is automatically assigned.

Creating Variables

Example Description
x = 10 Stores integer value
name = "Mohit" Stores text (string)
price = 99.5 Stores decimal (float)
is_active = True Stores boolean value

Rules for Naming Variables

Rule Example
Must start with letter or underscore name, _value
Cannot start with number ❌ 1name
No spaces allowed ❌ my name
Use meaningful names student_name

Example


                name = "Mohit"
                age = 20
                marks = 85.5
                
                print(name)
                print(age)
                print(marks)
                    

Multiple Assignment


                x, y, z = 10, 20, 30
                print(x, y, z)
                    

Changing Variable Value


                x = 5
                x = 10   # value changed
                print(x)
                    

When to Use Variables

  • Storing user input
  • Performing calculations
  • Saving data for reuse
  • Building programs and applications

Important Concepts

  • Variables do not need type declaration
  • Value can be changed anytime
  • Variable names should be meaningful

Tips

  • Use clear names like student_name
  • Follow lowercase naming style
  • Avoid using reserved keywords

Common Mistakes

  • Using numbers at start ❌
  • Using spaces in names ❌
  • Confusing uppercase/lowercase ❌

🎯 Practice Task

  • Create variables for name, age, and marks
  • Print all variables
  • Change value of one variable
  • Use multiple assignment

Data Types in Python

Data Types define the type of value a variable can hold. Python automatically detects the data type based on the value assigned.

Understanding data types is important for performing operations correctly in programs.

Common Data Types

Data Type Example Description
int 10 Whole numbers
float 10.5 Decimal numbers
str "Hello" Text or string
bool True / False Boolean values

Example


                x = 10          # int
                y = 5.5         # float
                name = "Mohit"  # string
                is_active = True  # boolean
                
                print(x)
                print(y)
                print(name)
                print(is_active)
                    

Checking Data Type

You can check the type of a variable using type() function.


                x = 10
                print(type(x))
                    

Type Conversion

Convert one data type into another using built-in functions.


                x = 10
                y = float(x)   # convert int to float
                
                print(y)
                    

When to Use Data Types

  • Performing calculations (int, float)
  • Working with text (string)
  • Making decisions (boolean)
  • Storing structured data

Important Concepts

  • Python is dynamically typed
  • Same variable can store different data types
  • Operations depend on data type

Tips

  • Use correct data type for correct operation
  • Use type() to debug issues
  • Convert types carefully

Common Mistakes

  • Mixing string and number ❌
  • Wrong type conversion ❌
  • Assuming type without checking ❌

🎯 Practice Task

  • Create variables of all data types
  • Use type() to check each variable
  • Convert int to float
  • Try converting string to number

Input & Output in Python

Input allows users to enter data into a program, while Output displays the result on the screen.

Python provides simple functions like input() and print() to handle user interaction.

Output using print()

Example Description
print("Hello") Displays text on screen
print(10 + 5) Displays result of calculation
print("Hi", "Mohit") Prints multiple values

Input using input()

The input() function takes user input as a string.


                name = input("Enter your name: ")
                print("Hello", name)
                    

Example Program


                name = input("Enter your name: ")
                age = input("Enter your age: ")
                
                print("Name:", name)
                print("Age:", age)
                    

Type Conversion with Input

Since input() returns a string, you need to convert it for calculations.


                num1 = int(input("Enter first number: "))
                num2 = int(input("Enter second number: "))
                
                sum = num1 + num2
                print("Sum is:", sum)
                    

Formatted Output


                name = "Mohit"
                age = 20
                
                print(f"My name is {name} and I am {age} years old")
                    

When to Use Input & Output

  • Taking user details
  • Performing calculations
  • Building interactive programs
  • Displaying results clearly

Important Concepts

  • input() always returns string
  • Use int() or float() for numbers
  • print() displays output instantly

Tips

  • Use clear prompts in input()
  • Always convert input when needed
  • Use f-strings for clean output

Common Mistakes

  • Not converting input to number ❌
  • Forgetting quotes in print ❌
  • Confusing string with number ❌

🎯 Practice Task

  • Take name input and print greeting
  • Take two numbers and print sum
  • Use f-string for formatted output
  • Create simple calculator using input()

Operators in Python

Operators are symbols used to perform operations on variables and values. They are used for calculations, comparisons, and logical decisions.

Python provides different types of operators for different purposes.

Types of Operators

Type Example Description
Arithmetic +, -, *, / Used for calculations
Comparison ==, !=, >, << /td> Compare values
Logical and, or, not Combine conditions
Assignment =, +=, -= Assign values to variables

Arithmetic Operators


                x = 10
                y = 5
                
                print(x + y)   # Addition
                print(x - y)   # Subtraction
                print(x * y)   # Multiplication
                print(x / y)   # Division
                print(x % y)   # Modulus
                    

Comparison Operators


                x = 10
                y = 5
                
                print(x > y)
                print(x == y)
                print(x != y)
                    

Logical Operators


                x = 10
                
                print(x > 5 and x < 20)
                print(x > 5 or x > 20)
                print(not(x > 5))
                    

Assignment Operators


                x = 10
                x += 5   # x = x + 5
                x -= 3   # x = x - 3
                
                print(x)
                    

Example Program


                num1 = 20
                num2 = 10
                
                print("Addition:", num1 + num2)
                print("Is num1 greater?", num1 > num2)
                    

When to Use Operators

  • Performing calculations
  • Making decisions
  • Updating variable values
  • Combining conditions

Important Concepts

  • Operators follow precedence rules
  • Comparison operators return True or False
  • Logical operators combine conditions

Tips

  • Use parentheses for clarity
  • Understand operator precedence
  • Use logical operators carefully

Common Mistakes

  • Using = instead of == ❌
  • Wrong operator precedence ❌
  • Confusing logical conditions ❌

🎯 Practice Task

  • Perform all arithmetic operations
  • Compare two numbers
  • Use logical operators in conditions
  • Update variable using assignment operators

If Else Conditions in Python

If Else statements are used to make decisions in a program. They allow your code to execute different blocks based on conditions.

Conditions return either True or False, and based on that, Python decides which block of code to run.

Basic If Statement


                age = 18
                
                if age >= 18:
                    print("You are eligible to vote")
                    

If Else Statement


                age = 16
                
                if age >= 18:
                    print("Eligible")
                else:
                    print("Not Eligible")
                    

If Elif Else Statement


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

Nested If Statement


                age = 20
                citizen = True
                
                if age >= 18:
                    if citizen:
                        print("Eligible to vote")
                    

Comparison Operators Used

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

Example Program


                num = int(input("Enter a number: "))
                
                if num % 2 == 0:
                    print("Even Number")
                else:
                    print("Odd Number")
                    

When to Use If Else

  • Making decisions in programs
  • Validating user input
  • Creating conditions in games
  • Controlling program flow

Important Concepts

  • Indentation is required
  • Condition must return True or False
  • elif is used for multiple conditions

Tips

  • Keep conditions simple and clear
  • Use logical operators for complex conditions
  • Test all possible cases

Common Mistakes

  • Missing indentation ❌
  • Using = instead of == ❌
  • Wrong condition logic ❌

🎯 Practice Task

  • Check if a number is positive or negative
  • Create a grade system using marks
  • Check if a number is even or odd
  • Use nested if for login validation

Loops in Python (for, while)

Loops are used to repeat a block of code multiple times. They help reduce repetition and make programs efficient.

Python mainly provides two types of loops: for loop and while loop.

Types of Loops

Loop Description
for loop Used when number of iterations is known
while loop Used when condition-based repetition is required

For Loop Example


                for i in range(1, 6):
                    print(i)
                    

This loop prints numbers from 1 to 5.

While Loop Example


                i = 1
                
                while i <= 5:
                    print(i)
                    i += 1
                    

This loop runs until the condition becomes false.

Break Statement

Used to stop the loop immediately.


                for i in range(1, 10):
                    if i == 5:
                        break
                    print(i)
                    

Continue Statement

Skips current iteration and continues with next.


                for i in range(1, 6):
                    if i == 3:
                        continue
                    print(i)
                    

Nested Loops


                for i in range(1, 4):
                    for j in range(1, 4):
                        print(i, j)
                    

Example Program


                # Print multiplication table of 5
                for i in range(1, 11):
                    print("5 x", i, "=", 5 * i)
                    

When to Use Loops

  • Repeating tasks
  • Iterating over data
  • Generating patterns
  • Processing lists and collections

Important Concepts

  • Infinite loop occurs if condition never becomes false
  • range() is commonly used with for loop
  • Loops can be nested

Tips

  • Use for loop when iterations are fixed
  • Use while loop for conditions
  • Be careful with infinite loops

Common Mistakes

  • Forgetting to update variable in while loop ❌
  • Wrong range values ❌
  • Creating infinite loops ❌

🎯 Practice Task

  • Print numbers from 1 to 10 using for loop
  • Print numbers using while loop
  • Create multiplication table
  • Use break and continue in loop

Lists in Python

A list is a collection of items stored in a single variable. It is one of the most commonly used data structures in Python.

Lists can store multiple values of different data types and are ordered and changeable.

Creating a List

Example Description
numbers = [1, 2, 3] List of integers
names = ["Mohit", "Shyam"] List of strings
mixed = [10, "Mohit", 5.5] Mixed data types

Accessing List Elements


                students = ["Ram", "Shyam", "Aman"]
                
                print(students[0])   # First element
                print(students[1])   # Second element
                    

Negative Indexing


                print(students[-1])  # Last element
                    

List Operations

Operation Example
Add Item list.append("New")
Insert Item list.insert(1, "Item")
Remove Item list.remove("Ram")
Delete Item del list[0]

Example Program


                fruits = ["Apple", "Banana", "Mango"]
                
                fruits.append("Orange")
                fruits.remove("Banana")
                
                print(fruits)
                    

Looping Through List


                for item in fruits:
                    print(item)
                    

When to Use Lists

  • Storing multiple values
  • Managing collections of data
  • Working with user input lists
  • Building applications

Important Concepts

  • Lists are ordered and indexed
  • Lists are mutable (can be changed)
  • Allow duplicate values

Tips

  • Use meaningful list names
  • Use loops to process lists
  • Keep lists organized

Common Mistakes

  • Index out of range ❌
  • Removing non-existing item ❌
  • Confusing list with string ❌

🎯 Practice Task

  • Create a list of 5 numbers
  • Add and remove elements
  • Print all elements using loop
  • Access first and last element

Tuples & Sets in Python

Tuples and Sets are important data structures in Python used to store collections of data.

While both store multiple values, they have different properties and use cases.

Tuple (Immutable Collection)

A tuple is an ordered collection of items that cannot be changed after creation.

Feature Description
Ordered Items maintain order
Immutable Cannot be changed
Allows Duplicates Same values allowed

Tuple Example


                colors = ("Red", "Green", "Blue")
                
                print(colors[0])
                    

Set (Unordered Collection)

A set is an unordered collection of unique items. It does not allow duplicate values.

Feature Description
Unordered No fixed order
No Duplicates Unique values only
Mutable Can add or remove items

Set Example


                numbers = {1, 2, 3, 3, 4}
                
                print(numbers)  # Duplicate removed
                    

Set Operations

Operation Example
Add Item set.add(5)
Remove Item set.remove(2)
Union set1 | set2
Intersection set1 & set2

Example Program


                set1 = {1, 2, 3}
                set2 = {3, 4, 5}
                
                print("Union:", set1 | set2)
                print("Intersection:", set1 & set2)
                    

When to Use Tuples & Sets

  • Tuple → When data should not change
  • Set → When you need unique values
  • Set → Removing duplicates from list
  • Tuple → Fixed data like coordinates

Important Concepts

  • Tuple uses ( ) and Set uses { }
  • Set does not maintain order
  • Tuple is faster than list

Tips

  • Use tuple for fixed data
  • Use set for unique elements
  • Convert list to set to remove duplicates

Common Mistakes

  • Trying to change tuple ❌
  • Expecting ordered data in set ❌
  • Confusing {} with dictionary ❌

🎯 Practice Task

  • Create a tuple and access elements
  • Create a set with duplicate values
  • Perform union and intersection
  • Convert list into set

Dictionaries in Python

A dictionary is a collection of data stored in key-value pairs. It is used to store related information in a structured way.

Dictionaries are unordered, changeable, and do not allow duplicate keys.

Creating a Dictionary

Example Description
student = {"name": "Mohit", "age": 20} Basic dictionary
data = {"a": 1, "b": 2} Key-value pairs
mixed = {"name": "Mohit", "marks": 85.5} Mixed data types

Accessing Values


                                student = {"name": "Mohit", "age": 20}
                                
                                print(student["name"])
                                print(student.get("age"))
                                    

Adding & Updating Items


                                student["marks"] = 90   # Add new key
                                student["age"] = 21     # Update value
                                    

Removing Items


                                student.pop("age")
                                del student["name"]
                                    

Dictionary Methods

Method Description
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs

Looping Through Dictionary


                                for key, value in student.items():
                                    print(key, ":", value)
                                    

Example Program


                                student = {
                                    "name": "Mohit",
                                    "age": 20,
                                    "marks": 85
                                }
                                
                                print("Name:", student["name"])
                                print("Marks:", student["marks"])
                                    

When to Use Dictionaries

  • Storing structured data
  • Managing user details
  • Working with APIs and JSON data
  • Building real-world applications

Important Concepts

  • Keys must be unique
  • Values can be any data type
  • Access using key, not index

Tips

  • Use meaningful keys
  • Use get() to avoid errors
  • Keep data structured

Common Mistakes

  • Using duplicate keys ❌
  • Accessing non-existing key ❌
  • Confusing dictionary with list ❌

🎯 Practice Task

  • Create a student dictionary
  • Add and update values
  • Loop through dictionary
  • Use keys(), values(), items()

Functions in Python

A function is a block of code that performs a specific task. It helps in reusing code and makes programs more organized.

Instead of writing the same code again and again, you can define a function and call it whenever needed.

Creating a Function

Keyword Description
def Used to define a function
() Used to pass parameters
return Returns value from function

Basic Function Example


                def greet():
                    print("Hello, Welcome!")
                
                greet()
                    

Function with Parameters


                def greet(name):
                    print("Hello", name)
                
                greet("Mohit")
                    

Function with Return Value


                def add(a, b):
                    return a + b
                
                result = add(10, 5)
                print(result)
                    

Default Parameters


                def greet(name="User"):
                    print("Hello", name)
                
                greet()
                greet("Mohit")
                    

Lambda Function


                add = lambda a, b: a + b
                print(add(3, 4))
                    

Example Program


                def square(num):
                    return num * num
                
                print(square(5))
                    

When to Use Functions

  • Reusing code
  • Organizing large programs
  • Improving readability
  • Breaking complex problems into smaller parts

Important Concepts

  • Function must be defined before calling
  • Parameters receive input values
  • Return sends output back

Tips

  • Use meaningful function names
  • Keep functions small and simple
  • Avoid repeating code

Common Mistakes

  • Forgetting to call function ❌
  • Missing return statement ❌
  • Wrong number of arguments ❌

🎯 Practice Task

  • Create a function to add two numbers
  • Create a function with default parameter
  • Use lambda to multiply two numbers
  • Create function to calculate square

Modules & Packages in Python

Modules and Packages help organize Python code into reusable files and folders. They make programs more structured and easier to manage.

Instead of writing all code in one file, you can split it into multiple modules.

What is a Module?

A module is a file that contains Python code (functions, variables, classes). It has a .py extension.

Example Description
math.py Custom module file
import math Built-in module

Using Built-in Modules


                import math
                
                print(math.sqrt(16))
                print(math.pi)
                    

Import Specific Functions


                from math import sqrt
                
                print(sqrt(25))
                    

Create Your Own Module


                # file: mymodule.py
                def greet(name):
                    print("Hello", name)
                    

                # main file
                import mymodule
                
                mymodule.greet("Mohit")
                    

What is a Package?

A package is a folder that contains multiple modules. It helps organize large projects.

Package Structure Example


                myproject/
                │
                ├── main.py
                ├── utils/
                │   ├── __init__.py
                │   ├── math_utils.py
                │   └── string_utils.py
                    

Import from Package


                from utils.math_utils import add
                
                print(add(5, 3))
                    

When to Use Modules & Packages

  • Organizing large projects
  • Reusing code
  • Separating logic into files
  • Building scalable applications

Important Concepts

  • Module = Single file
  • Package = Folder of modules
  • Use import to access modules

Tips

  • Keep modules small and focused
  • Use meaningful names
  • Organize code logically

Common Mistakes

  • Wrong import path ❌
  • Missing __init__.py in package ❌
  • Naming conflict with built-in modules ❌

🎯 Practice Task

  • Use math module to calculate square root
  • Create your own module
  • Import and use custom function
  • Create a simple package structure

File Handling in Python

File Handling allows you to create, read, write, and manage files. It is useful for storing data permanently instead of losing it after program execution.

Python provides built-in functions to work with files easily.

Opening a File

Use the open() function to open a file.


                file = open("data.txt", "r")
                    
Mode Description
"r" Read file
"w" Write (overwrite file)
"a" Append (add data)
"x" Create new file

Reading a File


                file = open("data.txt", "r")
                print(file.read())
                file.close()
                    

Writing to a File


                file = open("data.txt", "w")
                file.write("Hello Python")
                file.close()
                    

Appending to a File


                file = open("data.txt", "a")
                file.write("\nNew Line Added")
                file.close()
                    

Using with Statement (Best Practice)


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

The with statement automatically closes the file.

Example Program


                with open("student.txt", "w") as file:
                    file.write("Name: Mohit\nMarks: 90")
                
                with open("student.txt", "r") as file:
                    print(file.read())
                    

When to Use File Handling

  • Saving user data
  • Storing logs
  • Reading configuration files
  • Working with large datasets

Important Concepts

  • Always close files after use
  • Use correct mode (r, w, a)
  • File path must be correct

Tips

  • Use with for safe file handling
  • Check file existence before reading
  • Use newline (\n) for formatting

Common Mistakes

  • Forgetting to close file ❌
  • Wrong file mode ❌
  • File not found error ❌

🎯 Practice Task

  • Create and write data to a file
  • Read file content
  • Append new data
  • Use with statement

Exception Handling in Python

Exception Handling is used to handle errors in a program. It prevents the program from crashing and allows smooth execution.

Errors that occur during program execution are called exceptions.

Common Errors

Error Description
ZeroDivisionError Dividing by zero
ValueError Invalid input type
IndexError Invalid list index
FileNotFoundError File not found

Basic Try-Except


                try:
                    x = int(input("Enter number: "))
                    print(10 / x)
                except:
                    print("Error occurred")
                    

Handling Specific Exceptions


                try:
                    x = int(input("Enter number: "))
                    print(10 / x)
                
                except ZeroDivisionError:
                    print("Cannot divide by zero")
                
                except ValueError:
                    print("Invalid input")
                    

Using Else Block


                try:
                    x = 5
                    print(x)
                
                except:
                    print("Error")
                
                else:
                    print("No error occurred")
                    

Using Finally Block


                try:
                    file = open("data.txt", "r")
                
                except FileNotFoundError:
                    print("File not found")
                
                finally:
                    print("Execution completed")
                    

Raising Exceptions


                age = -5
                
                if age < 0:
                    raise ValueError("Age cannot be negative")
                    

Example Program


                try:
                    num1 = int(input("Enter number: "))
                    num2 = int(input("Enter number: "))
                    print(num1 / num2)
                
                except Exception as e:
                    print("Error:", e)
                    

When to Use Exception Handling

  • Handling user input errors
  • Working with files
  • Preventing program crashes
  • Building robust applications

Important Concepts

  • try → risky code
  • except → handle error
  • else → runs if no error
  • finally → always runs

Tips

  • Handle specific exceptions
  • Avoid using bare except
  • Use finally for cleanup tasks

Common Mistakes

  • Using only except without type ❌
  • Ignoring errors silently ❌
  • Wrong indentation ❌

🎯 Practice Task

  • Handle division by zero
  • Handle invalid input
  • Use finally block
  • Raise custom exception

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming style that uses classes and objects to organize code.

It helps in writing reusable, structured, and scalable programs.

Key Concepts of OOP

Concept Description
Class Blueprint for creating objects
Object Instance of a class
Encapsulation Wrapping data and methods together
Inheritance One class inherits another
Polymorphism Same function behaves differently

Creating a Class


                                class Student:
                                    name = "Mohit"
                                    age = 18
                                    

Creating an Object


                                s1 = Student()
                                print(s1.name)
                                print(s1.age)
                                    

Using Constructor (__init__)


                                class Student:
                                    def __init__(self, name, age):
                                        self.name = name
                                        self.age = age
                                
                                s1 = Student("Mohit", 18)
                                print(s1.name)
                                    

Instance Methods


                                class Student:
                                    def __init__(self, name):
                                        self.name = name
                                
                                    def greet(self):
                                        print("Hello, my name is", self.name)
                                
                                s1 = Student("Mohit")
                                s1.greet()
                                    

Inheritance


                                class Person:
                                    def show(self):
                                        print("This is a person")
                                
                                class Student(Person):
                                    def display(self):
                                        print("This is a student")
                                
                                s1 = Student()
                                s1.show()
                                    

Polymorphism


                                class Dog:
                                    def sound(self):
                                        print("Bark")
                                
                                class Cat:
                                    def sound(self):
                                        print("Meow")
                                
                                for animal in (Dog(), Cat()):
                                    animal.sound()
                                    

Encapsulation


                                class Student:
                                    def __init__(self):
                                        self.__marks = 0
                                
                                    def set_marks(self, marks):
                                        self.__marks = marks
                                
                                    def get_marks(self):
                                        return self.__marks
                                
                                s1 = Student()
                                s1.set_marks(90)
                                print(s1.get_marks())
                                    

Example Program


                                class Calculator:
                                    def add(self, a, b):
                                        return a + b
                                
                                c = Calculator()
                                print(c.add(5, 3))
                                    

When to Use OOP

  • Building large applications
  • Code reusability
  • Managing complex data
  • Real-world modeling

Important Concepts

  • Class → blueprint
  • Object → real instance
  • __init__ → constructor
  • self → refers to current object

Tips

  • Use meaningful class names
  • Keep methods simple
  • Use inheritance wisely

Common Mistakes

  • Forgetting 'self' ❌
  • Wrong indentation ❌
  • Not using __init__ properly ❌

🎯 Practice Task

  • Create a class for Student
  • Add name and marks using constructor
  • Create method to display details
  • Use inheritance

Inheritance in Python

Inheritance is a feature of OOP that allows one class to inherit properties and methods from another class.

It helps in code reusability and reduces duplication.

Key Terms

Term Description
Parent Class Class whose properties are inherited
Child Class Class that inherits from parent
super() Used to access parent class methods

Basic Inheritance


                                class Parent:
                                    def show(self):
                                        print("This is parent class")
                                
                                class Child(Parent):
                                    pass
                                
                                c = Child()
                                c.show()
                                    

Using Child Class Methods


                                class Parent:
                                    def show(self):
                                        print("Parent method")
                                
                                class Child(Parent):
                                    def display(self):
                                        print("Child method")
                                
                                c = Child()
                                c.show()
                                c.display()
                                    

Using super()


                                class Parent:
                                    def __init__(self):
                                        print("Parent constructor")
                                
                                class Child(Parent):
                                    def __init__(self):
                                        super().__init__()
                                        print("Child constructor")
                                
                                c = Child()
                                    

Types of Inheritance

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

Multiple Inheritance


                                class A:
                                    def methodA(self):
                                        print("Class A")
                                
                                class B:
                                    def methodB(self):
                                        print("Class B")
                                
                                class C(A, B):
                                    pass
                                
                                obj = C()
                                obj.methodA()
                                obj.methodB()
                                    

Multilevel Inheritance


                                class Grandparent:
                                    def show1(self):
                                        print("Grandparent")
                                
                                class Parent(Grandparent):
                                    def show2(self):
                                        print("Parent")
                                
                                class Child(Parent):
                                    def show3(self):
                                        print("Child")
                                
                                c = Child()
                                c.show1()
                                c.show2()
                                c.show3()
                                    

Method Overriding


                                class Parent:
                                    def show(self):
                                        print("Parent method")
                                
                                class Child(Parent):
                                    def show(self):
                                        print("Child method")
                                
                                c = Child()
                                c.show()
                                    

Example Program


                                class Animal:
                                    def sound(self):
                                        print("Animal makes sound")
                                
                                class Dog(Animal):
                                    def sound(self):
                                        print("Dog barks")
                                
                                d = Dog()
                                d.sound()
                                    

Advantages of Inheritance

  • Code reusability
  • Better organization
  • Easy maintenance

Important Concepts

  • Parent → base class
  • Child → derived class
  • super() → access parent methods
  • Overriding → redefining method

Tips

  • Use inheritance only when needed
  • Avoid deep inheritance chains
  • Prefer composition in complex cases

Common Mistakes

  • Forgetting super() ❌
  • Incorrect method overriding ❌
  • Confusion in multiple inheritance ❌

🎯 Practice Task

  • Create Parent and Child class
  • Use constructor with super()
  • Override a method
  • Create multilevel inheritance example

Polymorphism in Python

Polymorphism means "many forms". It allows the same function or method to behave differently based on the object.

It improves flexibility and reusability in programs.

Key Concepts

Concept Description
Method Overriding Same method name, different behavior
Operator Overloading Same operator, different meaning
Duck Typing Object type doesn't matter, behavior matters

Method Overriding


                                class Animal:
                                    def sound(self):
                                        print("Animal sound")
                                
                                class Dog(Animal):
                                    def sound(self):
                                        print("Dog barks")
                                
                                d = Dog()
                                d.sound()
                                    

Operator Overloading


                                print(5 + 3)        # Addition
                                print("Hello " + "World")  # String concatenation
                                    

Using Special Methods


                                class Number:
                                    def __init__(self, value):
                                        self.value = value
                                
                                    def __add__(self, other):
                                        return self.value + other.value
                                
                                n1 = Number(5)
                                n2 = Number(3)
                                print(n1 + n2)
                                    

Duck Typing


                                class Dog:
                                    def speak(self):
                                        print("Bark")
                                
                                class Cat:
                                    def speak(self):
                                        print("Meow")
                                
                                def make_sound(animal):
                                    animal.speak()
                                
                                make_sound(Dog())
                                make_sound(Cat())
                                    

Example Program


                                class Shape:
                                    def area(self):
                                        pass
                                
                                class Square(Shape):
                                    def area(self):
                                        return 4 * 4
                                
                                class Circle(Shape):
                                    def area(self):
                                        return 3.14 * 2 * 2
                                
                                for obj in (Square(), Circle()):
                                    print(obj.area())
                                    

Advantages of Polymorphism

  • Improves code flexibility
  • Enhances readability
  • Supports code reusability

Important Concepts

  • Same method → different behavior
  • Works with inheritance
  • Reduces code complexity

Tips

  • Use meaningful method names
  • Follow consistent structure
  • Use overriding carefully

Common Mistakes

  • Confusing overloading with overriding ❌
  • Incorrect method definitions ❌
  • Not understanding duck typing ❌

🎯 Practice Task

  • Create two classes with same method name
  • Implement method overriding
  • Create custom operator using __add__
  • Use duck typing function

Decorators in Python

Decorators are functions that modify the behavior of another function without changing its code.

They are commonly used for logging, authentication, timing, and more.

Key Concepts

Concept Description
Decorator Function that wraps another function
@ Syntax Shortcut to apply decorators
Wrapper Function Inner function that adds functionality

Basic Function Example


                                def greet():
                                    print("Hello")
                                
                                def my_decorator(func):
                                    def wrapper():
                                        print("Before function")
                                        func()
                                        print("After function")
                                    return wrapper
                                
                                greet = my_decorator(greet)
                                greet()
                                    

Using @ Decorator Syntax


                                def my_decorator(func):
                                    def wrapper():
                                        print("Before")
                                        func()
                                        print("After")
                                    return wrapper
                                
                                @my_decorator
                                def greet():
                                    print("Hello")
                                
                                greet()
                                    

Decorators with Arguments


                                def my_decorator(func):
                                    def wrapper(name):
                                        print("Before")
                                        func(name)
                                        print("After")
                                    return wrapper
                                
                                @my_decorator
                                def greet(name):
                                    print("Hello", name)
                                
                                greet("Mohit")
                                    

Using *args and **kwargs


                                def my_decorator(func):
                                    def wrapper(*args, **kwargs):
                                        print("Before")
                                        func(*args, **kwargs)
                                        print("After")
                                    return wrapper
                                
                                @my_decorator
                                def add(a, b):
                                    print(a + b)
                                
                                add(5, 3)
                                    

Real Example (Login Check)


                                def login_required(func):
                                    def wrapper():
                                        print("Checking login...")
                                        func()
                                    return wrapper
                                
                                @login_required
                                def dashboard():
                                    print("Welcome to dashboard")
                                
                                dashboard()
                                    

Example Program


                                def logger(func):
                                    def wrapper():
                                        print("Function started")
                                        func()
                                        print("Function ended")
                                    return wrapper
                                
                                @logger
                                def work():
                                    print("Working...")
                                
                                work()
                                    

Advantages of Decorators

  • Code reusability
  • Cleaner code
  • Add functionality without modifying original function

Important Concepts

  • @ → decorator syntax
  • wrapper → inner function
  • *args, **kwargs → flexible arguments

Tips

  • Use decorators for reusable logic
  • Keep wrapper simple
  • Use functools.wraps for best practice

Common Mistakes

  • Forgetting return in wrapper ❌
  • Not handling arguments properly ❌
  • Overcomplicating decorators ❌

🎯 Practice Task

  • Create a decorator to print before and after
  • Use decorator with arguments
  • Create login check decorator
  • Use *args and **kwargs

Generators in Python

Generators are special functions that return values one at a time using the yield keyword instead of return.

They are used to handle large data efficiently without storing everything in memory.

Key Concepts

Concept Description
Generator Function that yields values one by one
yield Pauses function and returns value
Iterator Object that can be looped over

Basic Generator Example


                                def count_up(n):
                                    i = 1
                                    while i <= n:
                                        yield i
                                        i += 1
                                
                                for num in count_up(5):
                                    print(num)
                                    

Using next()


                                def numbers():
                                    yield 1
                                    yield 2
                                    yield 3
                                
                                gen = numbers()
                                print(next(gen))
                                print(next(gen))
                                    

Generator vs Normal Function


                                def normal():
                                    return [1, 2, 3]
                                
                                def generator():
                                    yield 1
                                    yield 2
                                    yield 3
                                    

Generator Expression


                                nums = (x*x for x in range(5))
                                for n in nums:
                                    print(n)
                                    

Example Program


                                def even_numbers(n):
                                    for i in range(n):
                                        if i % 2 == 0:
                                            yield i
                                
                                for num in even_numbers(10):
                                    print(num)
                                    

Advantages of Generators

  • Memory efficient
  • Faster for large data
  • Lazy evaluation

Important Concepts

  • yield → returns value one at a time
  • next() → gets next value
  • Generators are iterators

Tips

  • Use generators for large datasets
  • Avoid storing big lists in memory
  • Use generator expressions when possible

Common Mistakes

  • Using return instead of yield ❌
  • Forgetting next() or loop ❌
  • Expecting generator to restart automatically ❌

🎯 Practice Task

  • Create generator for odd numbers
  • Use next() manually
  • Create generator expression
  • Compare list vs generator

Database (MySQL) in Python

MySQL is a popular database used to store and manage data. Python can connect to MySQL using libraries like mysql-connector.

It is widely used in web applications, data storage systems, and backend development.

Key Concepts

Concept Description
Database Collection of structured data
Table Data stored in rows and columns
Query Command to interact with database
Connector Library to connect Python with MySQL

Install MySQL Connector


                pip install mysql-connector-python
                    

Connecting to Database


                import mysql.connector
                
                conn = mysql.connector.connect(
                    host="localhost",
                    user="root",
                    password="your_password",
                    database="testdb"
                )
                
                print("Connected successfully")
                    

Create Database


                import mysql.connector
                
                conn = mysql.connector.connect(
                    host="localhost",
                    user="root",
                    password="your_password"
                )
                
                cursor = conn.cursor()
                cursor.execute("CREATE DATABASE mydb")
                    

Create Table


                cursor.execute("""
                CREATE TABLE students (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(50),
                    marks INT
                )
                """)
                    

Insert Data


                sql = "INSERT INTO students (name, marks) VALUES (%s, %s)"
                values = ("Mohit", 90)
                
                cursor.execute(sql, values)
                conn.commit()
                    

Fetch Data


                cursor.execute("SELECT * FROM students")
                
                for row in cursor.fetchall():
                    print(row)
                    

Update Data


                sql = "UPDATE students SET marks = %s WHERE name = %s"
                values = (95, "Mohit")
                
                cursor.execute(sql, values)
                conn.commit()
                    

Delete Data


                sql = "DELETE FROM students WHERE name = %s"
                values = ("Mohit",)
                
                cursor.execute(sql, values)
                conn.commit()
                    

Example Program


                import mysql.connector
                
                conn = mysql.connector.connect(
                    host="localhost",
                    user="root",
                    password="your_password",
                    database="mydb"
                )
                
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM students")
                
                for row in cursor:
                    print(row)
                    

Advantages of MySQL

  • Fast and reliable
  • Supports large data
  • Easy integration with Python

Important Concepts

  • Connection → connect to database
  • Cursor → execute queries
  • commit() → save changes

Tips

  • Always close connection after use
  • Use parameterized queries
  • Handle exceptions properly

Common Mistakes

  • Forgetting commit() ❌
  • Hardcoding SQL queries ❌
  • Not closing connection ❌

🎯 Practice Task

  • Create a database
  • Create students table
  • Insert and fetch data
  • Update and delete records

Working with APIs in Python

An API (Application Programming Interface) allows different applications to communicate with each other.

In Python, APIs are commonly used to fetch data from websites, send data to servers, and integrate services.

Key Concepts

Concept Description
API Interface for communication between systems
Request Sending data or asking for data
Response Data received from API
JSON Format used to exchange data

Install Requests Library


                pip install requests
                    

Making a GET Request


                import requests
                
                response = requests.get("https://api.example.com/data")
                
                print(response.status_code)
                print(response.text)
                    

Working with JSON Data


                import requests
                
                response = requests.get("https://api.example.com/data")
                
                data = response.json()
                
                print(data)
                    

Making a POST Request


                import requests
                
                url = "https://api.example.com/data"
                
                data = {
                    "name": "Mohit",
                    "marks": 90
                }
                
                response = requests.post(url, json=data)
                
                print(response.status_code)
                    

Handling Errors


                import requests
                
                try:
                    response = requests.get("https://api.example.com/data")
                    response.raise_for_status()
                    print(response.json())
                
                except requests.exceptions.RequestException as e:
                    print("Error:", e)
                    

Using API with Parameters


                import requests
                
                params = {
                    "q": "python",
                    "limit": 5
                }
                
                response = requests.get("https://api.example.com/search", params=params)
                
                print(response.json())
                    

Example Program


                import requests
                
                response = requests.get("https://api.example.com/users")
                
                if response.status_code == 200:
                    users = response.json()
                    for user in users:
                        print(user["name"])
                    

Advantages of APIs

  • Access real-time data
  • Integrate external services
  • Save development time

Important Concepts

  • GET → fetch data
  • POST → send data
  • JSON → data format
  • Status Code → response status

Tips

  • Always check status code
  • Handle exceptions properly
  • Secure API keys

Common Mistakes

  • Ignoring errors ❌
  • Not validating response ❌
  • Exposing API keys ❌

🎯 Practice Task

  • Fetch data using GET request
  • Send data using POST request
  • Work with JSON response
  • Handle API errors

Automation Scripts in Python

Automation means using Python to perform repetitive tasks automatically.

It saves time, reduces manual effort, and increases productivity.

Key Concepts

Concept Description
Automation Performing tasks automatically
Script Program written for a specific task
Scheduler Runs scripts at a specific time
Libraries Tools used for automation (os, shutil, etc.)

Working with Files (Automation)


                import os
                
                files = os.listdir()
                
                for file in files:
                    print(file)
                    

Rename Files Automatically


                import os
                
                files = os.listdir()
                
                for i, file in enumerate(files):
                    os.rename(file, f"file_{i}.txt")
                    

Move Files


                import shutil
                
                shutil.move("file.txt", "folder/file.txt")
                    

Send Email (Basic Example)


                import smtplib
                
                server = smtplib.SMTP("smtp.gmail.com", 587)
                server.starttls()
                
                server.login("your_email@gmail.com", "password")
                
                server.sendmail(
                    "your_email@gmail.com",
                    "receiver@gmail.com",
                    "Hello from Python"
                )
                
                server.quit()
                    

Open Websites Automatically


                import webbrowser
                
                webbrowser.open("https://google.com")
                    

Schedule Tasks


                import time
                
                while True:
                    print("Running task...")
                    time.sleep(5)  # runs every 5 seconds
                    

Example Program


                import os
                
                files = os.listdir()
                
                for file in files:
                    if file.endswith(".txt"):
                        print("Text file:", file)
                    

Popular Automation Libraries

  • os → file handling
  • shutil → file operations
  • smtplib → email automation
  • webbrowser → open websites
  • time → scheduling

Advantages of Automation

  • Saves time
  • Reduces errors
  • Improves efficiency

Important Concepts

  • Loop → repeat tasks
  • Script → automate process
  • Scheduler → run tasks automatically

Tips

  • Test scripts before automation
  • Use logging for tracking
  • Handle exceptions properly

Common Mistakes

  • Overwriting important files ❌
  • Hardcoding credentials ❌
  • Not handling errors ❌

🎯 Practice Task

  • Rename files automatically
  • Move files to folders
  • Create auto email script
  • Schedule a task

Web Development with Django

Django is a powerful Python framework used to build secure and scalable web applications.

It follows the MVT (Model-View-Template) architecture.

Key Concepts

Concept Description
Model Handles database structure
View Handles business logic
Template Frontend (HTML)
URL Routes user requests

Install Django


                pip install django
                    

Create Project


                django-admin startproject myproject
                cd myproject
                python manage.py runserver
                    

Create App


                python manage.py startapp myapp
                    

Project Structure


                myproject/
                    manage.py
                    myproject/
                        settings.py
                        urls.py
                    myapp/
                        views.py
                        models.py
                        admin.py
                    

Create View


                from django.http import HttpResponse
                
                def home(request):
                    return HttpResponse("Hello, Django!")
                    

Configure URL


                from django.contrib import admin
                from django.urls import path
                from myapp import views
                
                urlpatterns = [
                    path('', views.home),
                ]
                    

Create Template


                <!-- templates/home.html -->
                
                <h1>Welcome to Django</h1>
                    

Render Template


                from django.shortcuts import render
                
                def home(request):
                    return render(request, "home.html")
                    

Working with Models


                from django.db import models
                
                class Student(models.Model):
                    name = models.CharField(max_length=50)
                    marks = models.IntegerField()
                    

Migrations


                python manage.py makemigrations
                python manage.py migrate
                    

Admin Panel


                from django.contrib import admin
                from .models import Student
                
                admin.site.register(Student)
                    

Create Superuser


                python manage.py createsuperuser
                    

Example Program


                # views.py
                from django.shortcuts import render
                
                def home(request):
                    data = {"name": "Mohit"}
                    return render(request, "home.html", data)
                    

Advantages of Django

  • Fast development
  • Built-in admin panel
  • Secure and scalable

Important Concepts

  • MVT → architecture
  • Models → database
  • Views → logic
  • Templates → UI

Tips

  • Keep apps modular
  • Use virtual environments
  • Follow Django conventions

Common Mistakes

  • Not running migrations ❌
  • Wrong URL configuration ❌
  • Mixing logic in templates ❌

🎯 Practice Task

  • Create a Django project
  • Create app and views
  • Connect template
  • Create model and show data

NumPy in Python (Data Science)

NumPy (Numerical Python) is a powerful library used for numerical computations and working with arrays.

It is faster than Python lists and widely used in Data Science and Machine Learning.

Key Concepts

Concept Description
Array Collection of elements
ndarray NumPy's array object
Vectorization Fast operations on arrays
Broadcasting Operations on different-sized arrays

Install NumPy


                pip install numpy
                    

Create Arrays


                import numpy as np
                
                arr = np.array([1, 2, 3])
                print(arr)
                    

Array Operations


                import numpy as np
                
                a = np.array([1, 2, 3])
                b = np.array([4, 5, 6])
                
                print(a + b)
                print(a * b)
                    

Multi-Dimensional Arrays


                arr = np.array([[1, 2], [3, 4]])
                print(arr)
                    

Array Functions


                import numpy as np
                
                arr = np.array([1, 2, 3, 4])
                
                print(np.mean(arr))
                print(np.sum(arr))
                print(np.max(arr))
                    

Array Indexing


                arr = np.array([10, 20, 30])
                
                print(arr[0])
                print(arr[1])
                    

Reshaping Arrays


                arr = np.array([1, 2, 3, 4])
                
                new_arr = arr.reshape(2, 2)
                print(new_arr)
                    

Example Program


                import numpy as np
                
                arr = np.array([1, 2, 3, 4, 5])
                
                print("Sum:", np.sum(arr))
                print("Mean:", np.mean(arr))
                    

Advantages of NumPy

  • Faster than lists
  • Supports large datasets
  • Efficient mathematical operations

Important Concepts

  • array → core structure
  • vectorization → speed
  • broadcasting → flexibility

Tips

  • Use NumPy for heavy calculations
  • Avoid loops when possible
  • Use built-in functions

Common Mistakes

  • Mixing lists with arrays ❌
  • Wrong array shape ❌
  • Not using vectorization ❌

🎯 Practice Task

  • Create 1D and 2D arrays
  • Perform addition and multiplication
  • Find mean and sum
  • Reshape array

Pandas in Python (Data Analysis)

Pandas is a powerful Python library used for data analysis and data manipulation.

It provides easy-to-use data structures like Series and DataFrame.

Key Concepts

Concept Description
Series 1D labeled array
DataFrame 2D table (rows & columns)
Index Row labels
CSV Common file format for data

Install Pandas


                pip install pandas
                    

Create Series


                import pandas as pd
                
                s = pd.Series([10, 20, 30])
                print(s)
                    

Create DataFrame


                import pandas as pd
                
                data = {
                    "name": ["Mohit", "Aman"],
                    "marks": [90, 85]
                }
                
                df = pd.DataFrame(data)
                print(df)
                    

Read CSV File


                import pandas as pd
                
                df = pd.read_csv("data.csv")
                print(df)
                    

Basic Operations


                print(df.head())
                print(df.tail())
                print(df.shape)
                print(df.columns)
                    

Select Data


                print(df["name"])
                print(df.loc[0])
                    

Filter Data


                print(df[df["marks"] > 80])
                    

Add New Column


                df["grade"] = ["A", "B"]
                print(df)
                    

Handle Missing Data


                df.fillna(0, inplace=True)
                    

Example Program


                import pandas as pd
                
                data = {
                    "name": ["Mohit", "Aman", "Sohan"],
                    "marks": [90, 85, 88]
                }
                
                df = pd.DataFrame(data)
                
                print("Average:", df["marks"].mean())
                    

Advantages of Pandas

  • Easy data handling
  • Fast data processing
  • Works with large datasets

Important Concepts

  • Series → 1D data
  • DataFrame → table format
  • Index → labels

Tips

  • Use head() to preview data
  • Clean data before analysis
  • Use filters for better insights

Common Mistakes

  • Wrong column names ❌
  • Ignoring missing data ❌
  • Confusing loc and iloc ❌

🎯 Practice Task

  • Create DataFrame
  • Read CSV file
  • Filter data
  • Find average marks

Matplotlib in Python (Data Visualization)

Matplotlib is a popular Python library used for creating charts and graphs.

It helps visualize data in the form of line charts, bar charts, pie charts, etc.

Key Concepts

Concept Description
Plot Graph representation of data
Figure Whole graph window
Axes X and Y axis
Label Titles and names on graph

Install Matplotlib


                pip install matplotlib
                    

Basic Line Plot


                import matplotlib.pyplot as plt
                
                x = [1, 2, 3]
                y = [10, 20, 30]
                
                plt.plot(x, y)
                plt.show()
                    

Add Labels and Title


                plt.plot(x, y)
                
                plt.title("Simple Graph")
                plt.xlabel("X Axis")
                plt.ylabel("Y Axis")
                
                plt.show()
                    

Bar Chart


                x = ["A", "B", "C"]
                y = [5, 7, 3]
                
                plt.bar(x, y)
                plt.show()
                    

Pie Chart


                data = [30, 40, 30]
                
                plt.pie(data)
                plt.show()
                    

Multiple Plots


                plt.plot(x, y)
                plt.bar(x, y)
                
                plt.show()
                    

Example Program


                import matplotlib.pyplot as plt
                
                marks = [70, 80, 90, 85]
                
                plt.plot(marks)
                plt.title("Student Marks")
                plt.show()
                    

Advantages of Matplotlib

  • Easy to use
  • Supports multiple chart types
  • Customizable graphs

Important Concepts

  • plt → plotting module
  • plot() → line chart
  • show() → display graph

Tips

  • Always label your graphs
  • Use titles for clarity
  • Keep graphs simple

Common Mistakes

  • Forgetting plt.show() ❌
  • Incorrect data size ❌
  • No labels ❌

🎯 Practice Task

  • Create line graph
  • Create bar chart
  • Create pie chart
  • Add labels and title

Machine Learning Basics in Python

Machine Learning (ML) is a branch of AI that allows systems to learn from data and improve without being explicitly programmed.

It is widely used in prediction, recommendation systems, and data analysis.

Key Concepts

Concept Description
Dataset Collection of data
Features Input variables
Target Output variable
Model Algorithm that learns from data

Types of Machine Learning

  • Supervised Learning
  • Unsupervised Learning
  • Reinforcement Learning

Install Scikit-learn


                pip install scikit-learn
                    

Simple Linear Regression


                from sklearn.linear_model import LinearRegression
                import numpy as np
                
                X = np.array([[1], [2], [3], [4]])
                y = np.array([2, 4, 6, 8])
                
                model = LinearRegression()
                model.fit(X, y)
                
                print(model.predict([[5]]))
                    

Train-Test Split


                from sklearn.model_selection import train_test_split
                
                X_train, X_test, y_train, y_test = train_test_split(
                    X, y, test_size=0.2
                )
                    

Model Evaluation


                from sklearn.metrics import mean_squared_error
                
                pred = model.predict(X_test)
                print(mean_squared_error(y_test, pred))
                    

Classification Example


                from sklearn.tree import DecisionTreeClassifier
                
                X = [[1], [2], [3], [4]]
                y = [0, 0, 1, 1]
                
                model = DecisionTreeClassifier()
                model.fit(X, y)
                
                print(model.predict([[3]]))
                    

Example Program


                from sklearn.linear_model import LinearRegression
                import numpy as np
                
                X = np.array([[10], [20], [30]])
                y = np.array([100, 200, 300])
                
                model = LinearRegression()
                model.fit(X, y)
                
                print("Prediction:", model.predict([[40]]))
                    

Advantages of Machine Learning

  • Automates decision making
  • Handles large data
  • Improves over time

Important Concepts

  • Model → learns patterns
  • Training → learning phase
  • Prediction → output

Tips

  • Clean your data first
  • Choose correct algorithm
  • Avoid overfitting

Common Mistakes

  • Using wrong data ❌
  • Not splitting data ❌
  • Ignoring evaluation ❌

🎯 Practice Task

  • Create a linear regression model
  • Predict new values
  • Split data into train/test
  • Evaluate model

Project: Calculator App in Python

In this project, we will build a calculator using Python that runs in the terminal (CLI).

It will perform basic arithmetic operations like addition, subtraction, multiplication, and division.

Project Features

  • Menu-driven program
  • Handles user input
  • Error handling (division by zero)
  • Loop for continuous use

Step 1: Create File


                calculator.py
                    

Step 2: Define Functions


                def add(a, b):
                    return a + b
                
                def subtract(a, b):
                    return a - b
                
                def multiply(a, b):
                    return a * b
                
                def divide(a, b):
                    if b == 0:
                        return "Cannot divide by zero"
                    return a / b
                    

Step 3: User Menu


                print("Select Operation:")
                print("1. Add")
                print("2. Subtract")
                print("3. Multiply")
                print("4. Divide")
                    

Step 4: Main Program


                while True:
                    choice = input("Enter choice (1/2/3/4 or q to quit): ")
                
                    if choice == 'q':
                        break
                
                    if choice in ['1', '2', '3', '4']:
                        try:
                            num1 = float(input("Enter first number: "))
                            num2 = float(input("Enter second number: "))
                        except ValueError:
                            print("Invalid input")
                            continue
                
                        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 choice")
                    

Step 5: How It Works

  • User selects operation
  • Inputs numbers
  • Program calls function
  • Result is displayed
  • Loop continues until user exits

Example Run


                Select Operation:
                1. Add
                2. Subtract
                3. Multiply
                4. Divide
                
                Enter choice: 1
                Enter first number: 5
                Enter second number: 3
                Result: 8
                    

Advanced Version (Using eval)


                while True:
                    expr = input("Enter expression (or 'q' to quit): ")
                
                    if expr == 'q':
                        break
                
                    try:
                        print("Result:", eval(expr))
                    except:
                        print("Error")
                    

Important Concepts Used

  • Functions
  • Loops
  • Conditionals
  • Exception Handling

Tips

  • Always validate input
  • Handle division by zero
  • Use functions for clean code

Common Mistakes

  • Not handling invalid input ❌
  • Infinite loop without exit ❌
  • Using eval without try-except ❌

🎯 Practice Task

  • Add power operation
  • Add square root
  • Create GUI using Tkinter
  • Store calculation history

Project: To-Do App in Python

In this project, we will build a To-Do List application using Python that stores tasks in a file.

Users can add, view, and delete tasks easily.

Project Features

  • Add tasks
  • View tasks
  • Delete tasks
  • Data saved in file (persistent storage)

Step 1: Create File


                todo.py
                tasks.txt
                    

Step 2: Load Tasks from File


                def load_tasks():
                    try:
                        with open("tasks.txt", "r") as file:
                            tasks = file.readlines()
                        return [task.strip() for task in tasks]
                    except FileNotFoundError:
                        return []
                    

Step 3: Save Tasks to File


                def save_tasks(tasks):
                    with open("tasks.txt", "w") as file:
                        for task in tasks:
                            file.write(task + "\n")
                    

Step 4: Add Task


                def add_task(tasks):
                    task = input("Enter new task: ")
                    tasks.append(task)
                    save_tasks(tasks)
                    print("Task added!")
                    

Step 5: View Tasks


                def view_tasks(tasks):
                    if not tasks:
                        print("No tasks found.")
                        return
                
                    print("\nYour Tasks:")
                    for i, task in enumerate(tasks, start=1):
                        print(f"{i}. {task}")
                    

Step 6: Delete Task


                def delete_task(tasks):
                    view_tasks(tasks)
                    
                    try:
                        num = int(input("Enter task number to delete: "))
                        removed = tasks.pop(num - 1)
                        save_tasks(tasks)
                        print("Removed:", removed)
                    except:
                        print("Invalid input")
                    

Step 7: Main Program


                def main():
                    tasks = load_tasks()
                
                    while True:
                        print("\n1. View Tasks")
                        print("2. Add Task")
                        print("3. Delete Task")
                        print("4. Exit")
                
                        choice = input("Choose option: ")
                
                        if choice == "1":
                            view_tasks(tasks)
                
                        elif choice == "2":
                            add_task(tasks)
                
                        elif choice == "3":
                            delete_task(tasks)
                
                        elif choice == "4":
                            print("Goodbye!")
                            break
                
                        else:
                            print("Invalid choice")
                
                main()
                    

How It Works

  • Tasks are stored in tasks.txt
  • Program loads tasks at start
  • User performs operations
  • Changes are saved automatically

Example Run


                1. View Tasks
                2. Add Task
                3. Delete Task
                4. Exit
                
                Choose option: 2
                Enter new task: Study Python
                Task added!
                    

Important Concepts Used

  • File Handling
  • Lists
  • Functions
  • Loops
  • Exception Handling

Advanced Improvements

  • Add task deadlines
  • Mark tasks as completed
  • Create GUI using Tkinter
  • Use database instead of file

Tips

  • Always save after changes
  • Validate user input
  • Keep code modular

Common Mistakes

  • Forgetting to save file ❌
  • Wrong index while deleting ❌
  • Not handling empty list ❌

🎯 Practice Task

  • Add "mark as complete" feature
  • Add priority (High/Medium/Low)
  • Store tasks with date
  • Convert to GUI app

Project: Student Management System in Python

In this project, we will build a Student Management System using Python to manage student records.

It allows adding, viewing, searching, updating, and deleting student data.

Project Features

  • Add student details
  • View all students
  • Search student
  • Update student
  • Delete student
  • Data stored in file

Step 1: Create Files


                student.py
                students.txt
                    

Step 2: Load Data


                def load_students():
                    try:
                        with open("students.txt", "r") as file:
                            students = file.readlines()
                        return [s.strip().split(",") for s in students]
                    except FileNotFoundError:
                        return []
                    

Step 3: Save Data


                def save_students(students):
                    with open("students.txt", "w") as file:
                        for s in students:
                            file.write(",".join(s) + "\n")
                    

Step 4: Add Student


                def add_student(students):
                    name = input("Enter name: ")
                    roll = input("Enter roll number: ")
                    marks = input("Enter marks: ")
                
                    students.append([name, roll, marks])
                    save_students(students)
                
                    print("Student added!")
                    

Step 5: View Students


                def view_students(students):
                    if not students:
                        print("No records found.")
                        return
                
                    for s in students:
                        print(f"Name: {s[0]}, Roll: {s[1]}, Marks: {s[2]}")
                    

Step 6: Search Student


                def search_student(students):
                    roll = input("Enter roll number: ")
                
                    for s in students:
                        if s[1] == roll:
                            print(f"Found: {s}")
                            return
                
                    print("Student not found")
                    

Step 7: Update Student


                def update_student(students):
                    roll = input("Enter roll number: ")
                
                    for s in students:
                        if s[1] == roll:
                            s[0] = input("New name: ")
                            s[2] = input("New marks: ")
                            save_students(students)
                            print("Updated!")
                            return
                
                    print("Student not found")
                    

Step 8: Delete Student


                def delete_student(students):
                    roll = input("Enter roll number: ")
                
                    for s in students:
                        if s[1] == roll:
                            students.remove(s)
                            save_students(students)
                            print("Deleted!")
                            return
                
                    print("Student not found")
                    

Step 9: Main Menu


                def main():
                    students = load_students()
                
                    while True:
                        print("\n1. Add Student")
                        print("2. View Students")
                        print("3. Search Student")
                        print("4. Update Student")
                        print("5. Delete Student")
                        print("6. Exit")
                
                        choice = input("Enter choice: ")
                
                        if choice == "1":
                            add_student(students)
                
                        elif choice == "2":
                            view_students(students)
                
                        elif choice == "3":
                            search_student(students)
                
                        elif choice == "4":
                            update_student(students)
                
                        elif choice == "5":
                            delete_student(students)
                
                        elif choice == "6":
                            break
                
                        else:
                            print("Invalid choice")
                
                main()
                    

How It Works

  • Data stored in students.txt
  • Each student → name, roll, marks
  • Menu-driven program
  • All changes saved to file

Example Data Format


                Mohit,101,90
                Aman,102,85
                    

Important Concepts Used

  • File Handling
  • Lists & Nested Lists
  • Loops
  • Functions
  • Conditionals

Advanced Improvements

  • Use MySQL database instead of file
  • Create GUI using Tkinter
  • Add login system
  • Add marks calculation & grade

Tips

  • Keep roll number unique
  • Validate user input
  • Handle file errors properly

Common Mistakes

  • Duplicate roll numbers ❌
  • Wrong file format ❌
  • Not saving after update ❌

🎯 Practice Task

  • Add grade calculation
  • Sort students by marks
  • Convert to database version
  • Create GUI version

Project: Blog Website using Django

In this project, we will build a Blog Website using Django where users can create, view, and manage blog posts.

This is a real-world project used in platforms like Medium or WordPress.

Project Features

  • Create blog posts
  • View all posts
  • View single post
  • Admin panel for management
  • Database storage

Step 1: Install Django


                pip install django
                    

Step 2: Create Project


                django-admin startproject blogproject
                cd blogproject
                python manage.py startapp blog
                    

Step 3: Register App


                # settings.py
                INSTALLED_APPS = [
                    'blog',
                ]
                    

Step 4: Create Model


                # blog/models.py
                
                from django.db import models
                
                class Post(models.Model):
                    title = models.CharField(max_length=100)
                    content = models.TextField()
                    created_at = models.DateTimeField(auto_now_add=True)
                
                    def __str__(self):
                        return self.title
                    

Step 5: Run Migrations


                python manage.py makemigrations
                python manage.py migrate
                    

Step 6: Register Model in Admin


                # blog/admin.py
                
                from django.contrib import admin
                from .models import Post
                
                admin.site.register(Post)
                    

Step 7: Create Superuser


                python manage.py createsuperuser
                    

Step 8: Create Views


                # blog/views.py
                
                from django.shortcuts import render
                from .models import Post
                
                def home(request):
                    posts = Post.objects.all()
                    return render(request, "home.html", {"posts": posts})
                    

Step 9: Configure URLs


                # blog/urls.py
                
                from django.urls import path
                from . import views
                
                urlpatterns = [
                    path('', views.home),
                ]
                    

                # main urls.py
                
                from django.urls import path, include
                
                urlpatterns = [
                    path('', include('blog.urls')),
                ]
                    

Step 10: Create Template


                <!-- templates/home.html -->
                
                <h1>Blog Posts</h1>
                
                {% for post in posts %}
                    <h2>{{ post.title }}</h2>
                    <p>{{ post.content }}</p>
                    <hr>
                {% endfor %}
                    

Step 11: Run Server


                python manage.py runserver
                    

How It Works

  • Admin adds blog posts
  • Posts stored in database
  • Website fetches and displays posts

Example Output


                Blog Posts
                
                Title: My First Post
                Content: This is my blog content
                    

Important Concepts Used

  • Django Models
  • Views & Templates
  • URL Routing
  • Database (SQLite)

Advanced Features (Upgrade)

  • User login & signup
  • Comments system
  • Like/Dislike posts
  • Image upload
  • Search functionality

Tips

  • Keep templates clean
  • Use reusable components
  • Follow Django structure

Common Mistakes

  • Not running migrations ❌
  • Wrong URL config ❌
  • Missing templates folder ❌

🎯 Practice Task

  • Add post detail page
  • Add edit/delete option
  • Add user authentication
  • Add image upload

Project: File Organizer Automation Tool (Python)

In this project, we will build a File Organizer Tool using Python that automatically sorts files into folders.

It helps clean messy folders like Downloads by organizing files by type.

Project Features

  • Automatically sort files
  • Create folders by file type
  • Move files to correct folders
  • Works on any directory

Step 1: Create File


            organizer.py
                

Step 2: Import Modules


            import os
            import shutil
                

Step 3: Define Folder Path


            path = "C:/Users/YourName/Downloads"
            files = os.listdir(path)
                

Step 4: File Type Mapping


            file_types = {
                "Images": [".jpg", ".png", ".jpeg"],
                "Documents": [".pdf", ".docx", ".txt"],
                "Videos": [".mp4", ".mkv"],
                "Music": [".mp3"],
                "Programs": [".exe"]
            }
                

Step 5: Create Folders


            for folder in file_types:
                folder_path = os.path.join(path, folder)
                if not os.path.exists(folder_path):
                    os.makedirs(folder_path)
                

Step 6: Move Files


            for file in files:
                file_path = os.path.join(path, file)
            
                if os.path.isfile(file_path):
                    for folder, extensions in file_types.items():
                        for ext in extensions:
                            if file.endswith(ext):
                                shutil.move(file_path, os.path.join(path, folder, file))
                

Step 7: Run Script


            python organizer.py
                

How It Works

  • Reads all files in folder
  • Checks file extensions
  • Creates folders if needed
  • Moves files automatically

Example Before


            Downloads/
                file1.jpg
                notes.pdf
                song.mp3
                video.mp4
                

Example After


            Downloads/
                Images/
                Documents/
                Music/
                Videos/
                

Important Concepts Used

  • os module
  • shutil module
  • Loops
  • Dictionaries

Advanced Improvements

  • Auto-run daily (scheduler)
  • GUI using Tkinter
  • Undo feature
  • Custom rules (user input)

Tips

  • Test on sample folder first
  • Avoid moving system files
  • Use logs to track changes

Common Mistakes

  • Wrong folder path ❌
  • File already exists error ❌
  • Moving important files ❌

🎯 Practice Task

  • Add file size filter
  • Add rename feature
  • Create GUI version
  • Schedule auto-run

🎉 Course Completed!

Congratulations! You’ve successfully finished this course.