0% found this document useful (0 votes)
5 views25 pages

Python Shortnotes

The document provides a comprehensive overview of Python, covering its definition, features, applications, and key concepts such as identifiers, keywords, comments, variables, data types, control flow, functions, object-oriented programming, file handling, exception handling, and data structures. It highlights Python's ease of use, versatility, and importance in various fields like web development, data science, and automation. Additionally, it outlines the rules for naming identifiers and variables, the differences between data structures, and the principles of object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

Python Shortnotes

The document provides a comprehensive overview of Python, covering its definition, features, applications, and key concepts such as identifiers, keywords, comments, variables, data types, control flow, functions, object-oriented programming, file handling, exception handling, and data structures. It highlights Python's ease of use, versatility, and importance in various fields like web development, data science, and automation. Additionally, it outlines the rules for naming identifiers and variables, the differences between data structures, and the principles of object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BSDVP ACADEMY

Python – Short Notes


What is Python?
• Python is a high-level, interpreted, general-purpose programming language.
• Created by Guido van Rossum (1991).
• Designed to be simple, readable, and easy to learn.
• Uses indentation instead of braces {}.

Features of Python

• ✔ Easy to learn & beginner-friendly

• ✔ Interpreted language (no compilation required)

• ✔ Object-Oriented

• ✔ Dynamically Typed

• ✔ Portable (runs on Windows, Linux, Mac)

• ✔ Large standard library

• ✔ Supports multiple paradigms (OOP, Functional, Procedural)

Applications of Python
• Web Development (Django, Flask)
• Data Science & Machine Learning
• Automation & Scripting
• Cyber Security
• Networking
• Artificial Intelligence
• Game Development

\
BSDVP ACADEMY
Python Identifiers

Definition
• An identifier is the name given to:
• Variables
• Functions
• Classes
• Modules
• Objects
• It is used to identify a programming element in Python.

• Rules for Naming Identifiers


• Must start with a letter (A–Z or a–z) or an underscore (_)
✔ name, _value
1name
• Cannot start with a digit
123abc
• Can contain:
• Letters
• Digits
• Underscore (_)
• No special characters allowed
name@123
• Cannot use Python keywords
if, class, for
• Python is case-sensitive
• name, Name, and NAME are different.
Important Points for Entrance Exams
• Identifiers are user-defined names.
• Cannot use reserved keywords as identifiers.
• Must follow naming rules.
• Case sensitive.
BSDVP ACADEMY
• Underscore (_) is allowed.

Common Exam Questions

✔ Which of the following is a valid identifier?


✔ Why is for = 10 invalid?
✔ Is Student_Name different from student_name? (Yes – case sensitive)

Keywords in Python

Definition
Keywords are reserved words in Python that have special meanings and predefined
functions.
• They are part of Python’s syntax.
• They cannot be used as identifiers (variable names, function names, etc.).
• Examples of Python Keywords
• if else elif
• for while break
• continue pass
• def return
• class try except
• import from as
• True False None
• and or not

Comments in Python

Definition
Comments are non-executable statements used to explain the code.
• They are ignored by the Python interpreter.
• Used to improve readability and documentation.
• Do not affect program execution.
BSDVP ACADEMY

Types of Comments in Python

Single-Line Comment
• Starts with #
# This is a single-line comment
x = 10

Multi-Line Comment
Python does not have a separate multi-line comment symbol, but we use:
• Triple single quotes '''
• Triple double quotes """
"""
This is a
multi-line comment
"""

Purpose of Comments
• Explain logic
• Improve readability
• Debug code
• Provide documentation
• Make code easier to maintain

Variables in Python – Short Notes

Definition
A variable is a name used to store data in memory.
• It acts as a container for storing values.
• No need to declare data type explicitly.
BSDVP ACADEMY
• Python is dynamically typed (type is decided at runtime).

Variable Declaration
In Python, variables are created when a value is assigned.
e.g:-
x = 10
name = "Ram"
price = 99.5

Rules for Naming Variables


• Must follow identifier rules
• Can contain letters, digits, underscore
• Cannot start with a digit
• Cannot use keywords
• Case sensitive
e.g;-
student_name = "Chakrapani"

Data Types in Python – Short Notes


Python provides several built-in data types to store different kinds of data.

int (Integer)
• Stores whole numbers (positive or negative).
• No decimal point.
• Example:
x = 10
y = -25
float
• Stores decimal numbers.
• Used for real numbers.
Example:
pi = 3.14
BSDVP ACADEMY
price = 99.99

str (String)
• Stores sequence of characters.
• Written inside ' ' or " ".
Example:
name = "Python"

bool (Boolean)
• Stores only two values:
o True
o False
Example:
x = True
y = False

Difference Between Set and Dictionary

Feature Set Dictionary

Collection of unique
Definition Collection of key-value pairs
elements

Syntax {1, 2, 3} {"a": 1, "b": 2}

Data Storage Stores only values Stores key and value

Keys not allowed to duplicate (values can


Duplicates Not allowed
repeat)

Order Unordered Insertion order maintained (Python 3.7+)

Indexing Not allowed Access using keys

Keys Concept No keys Keys are mandatory

Mutability Mutable Mutable

Empty
set() {}
Declaration
BSDVP ACADEMY
Feature Set Dictionary

Example Use Removing duplicates Structured data storage

Difference Between List and Tuple

Feature List Tuple

Definition Ordered collection Ordered collection

Syntax [1,2,3] (1,2,3)

Mutability Mutable Immutable

Modification Can change Cannot change

Performance Slower Faster

Memory More memory Less memory

Methods Many built-in methods Limited methods

Use Case Dynamic data Fixed data

Hashable Not hashable Hashable (if elements are immutable)

Control Flow & Loops (Python)


Conditional Statements (Decision Making)

if Statement
• Executes block only if condition is True.
• Syntax:
if condition:
statement
• Indentation is mandatory.

if-else Statement
• Two-way decision making.
BSDVP ACADEMY
if condition:
block1
else:
block2
Used for:
• Even/Odd
• Positive/Negative

if-elif-else Ladder
• Multiple condition checking.
if condition1:
elif condition2:
else:
• Only one block executes.
• Used in grade calculation.

Nested if
• if inside another if.
• Used for complex decisions.

Ternary Operator (Short-hand if)


result = "Yes" if a>b else "No"

Operators in Control Flow

Comparison Operators
==, !=, >, <, >=, <=
Used to compare values.

Logical Operators
• and → Both True
• or → At least one True
BSDVP ACADEMY
• not → Reverse condition
Important for:
• Combining multiple conditions

Membership Operators
• in
• not in
Used to check presence in sequence.

Identity Operators
• is
• is not
Difference:
• == → compares values
• is → compares memory location

while Loop
• Repeats while condition is True.
while condition:
statement
• Used when number of iterations unknown.
• Risk of infinite loop.

for Loop
• Used for iterating sequences.
for variable in sequence:
statement
• Used when number of iterations known.

range() Function
Forms:
• range(stop)
• range(start, stop)
BSDVP ACADEMY
• range(start, stop, step)
Used mostly in for loops.

Nested Loops
• Loop inside another loop.
• Used in:
o Pattern programs
o Matrix problems
o Tables

Loop Control Statements

break
• Terminates loop immediately.

continue
• Skips current iteration.

pass
• Does nothing (placeholder).

Loop with else


• Executes when loop completes normally.
• Not executed if break is used.

Functions & Arrays

PART 1: FUNCTIONS IN PYTHON

Function – Definition
A function is a block of organized, reusable code that performs a specific task.
• Defined using def keyword.
• Helps in modular programming.
• Reduces code repetition.
Example:
def add(a, b):
BSDVP ACADEMY
return a + b

Built-in Function – Definition


A built-in function is a pre-defined function provided by Python.
Examples:
print(), len(), type(), range(), sum()

User-defined Function – Definition


A user-defined function is a function created by the programmer using the def keyword.

Parameters – Definition
Parameters are variables listed inside the parentheses in function definition.
Example:
def add(a, b):
Here a and b are parameters.

Arguments – Definition
Arguments are the actual values passed to a function when it is called.
Example:
add(10, 20)
Here 10 and 20 are arguments.

Return Statement – Definition


The return statement is used to send a value back to the function caller.
If no return statement → function returns None.

Lambda Function – Definition


A lambda function is an anonymous (nameless) function defined using the lambda keyword.
• Used for short, single-expression functions.
Example:
square = lambda x: x*x

Recursion – Definition
Recursion is a process in which a function calls itself.

Local Variable – Definition


A local variable is declared inside a function and can only be accessed within that function.
BSDVP ACADEMY
Global Variable – Definition
A global variable is declared outside all functions and can be accessed throughout the
program.

PART 2: ARRAYS IN PYTHON

⚠ Python mainly uses List as an array.

Array – Definition
An array is a collection of elements stored in contiguous memory locations.
• Stores multiple values in a single variable.
• Elements are accessed using index.

List – Definition
A list is an ordered, mutable collection of elements enclosed in square brackets [ ].
Example:
arr = [1, 2, 3]

Indexing – Definition
Indexing is accessing elements using their position number.
Example:
arr[0]

Slicing – Definition
Slicing is extracting a portion of a list or array using start and end index.
Example:
arr[1:3]

2D Array – Definition
A 2D array is a list of lists used to represent matrix-like data.
Example:
matrix = [[1,2],[3,4]]

Traversing – Definition
Traversing means visiting each element of an array or list one by one.
BSDVP ACADEMY
Object Oriented Programming (OOP) in Python

Object-Oriented Programming – Definition


Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
objects, which contain data (attributes) and functions (methods).

✔ Organizes code into reusable structures


✔ Improves modularity and security
✔ Based on real-world concepts

Class – Definition
A class is a blueprint or template used to create objects.
• Defined using class keyword.
• Contains variables (attributes) and functions (methods).
Example:
class Student:
pass

Object – Definition
An object is an instance of a class.
• Represents real-world entity.
• Has state (data) and behavior (functions).
Example:
s1 = Student()

Instance – Definition
An instance is a specific object created from a class.

✔ Object = Instance of class

Constructor (init) – Definition


A constructor is a special method that initializes object attributes.
• Automatically called when object is created.
BSDVP ACADEMY
• Defined using __init__().
Example:
class Student:
def __init__(self, name):
[Link] = name

self Keyword – Definition


self refers to the current object of the class.
• Used to access instance variables and methods.

Attributes – Definition
Attributes are variables inside a class.
Types:
• Instance variables
• Class variables

Methods – Definition
Methods are functions defined inside a class.
Types:
• Instance method
• Class method
• Static method

The Four Pillars of OOP (Very Important)

1. Encapsulation – Definition
Encapsulation is binding data and methods together in a single unit (class).

✔ Achieved using classes


✔ Data hiding using private variables
BSDVP ACADEMY
Example:
__salary

2. Abstraction – Definition
Abstraction means hiding internal implementation details and showing only essential
features.

✔ Achieved using abstract classes


✔ Focus on what object does, not how

3. Inheritance – Definition
Inheritance allows one class to acquire properties of another class.
class Child(Parent):
Types:
• Single
• Multiple
• Multilevel
• Hierarchical
• Hybrid

4. Polymorphism – Definition
Polymorphism means "many forms".
Same function name behaves differently.
Types:
• Method Overloading
• Method Overriding

Method Overloading
• Same method name with different parameters.
• Python supports through default arguments.
BSDVP ACADEMY

Method Overriding
• Child class redefines parent method.
File Handling & Exception Handling in Python
PART 1: FILE HANDLING IN PYTHON

File Handling – Definition


File Handling is the process of creating, opening, reading, writing, and closing files in a
program.

✔ Used for permanent data storage


✔ Data stored in external files

Opening a File
Syntax:
file = open("filename", "mode")
Example:
f = open("[Link]", "r")

File Modes (Very Important)

Mode Meaning

r Read (default)

w Write (overwrites file)

a Append

x Create new file

rb Read binary

wb Write binary

Reading a File
[Link]()
BSDVP ACADEMY
[Link]()
[Link]()

Writing to a File
[Link]("Hello")

Closing a File
[Link]()

✔ Always close file to free memory.

with Statement (Best Practice)


with open("[Link]", "r") as f:
print([Link]())

✔ Automatically closes file


✔ Avoids memory leaks

Important Differences
read() vs readline() vs readlines()

read() readline() readlines()

Reads full file Reads one line Returns list of lines

PART 2: EXCEPTION HANDLING IN PYTHON

Exception – Definition
An exception is an error that occurs during program execution.
Examples:
• ZeroDivisionError
• FileNotFoundError
• ValueError
BSDVP ACADEMY
• TypeError

Exception Handling – Definition


Exception Handling is the process of handling runtime errors using special blocks of code.

try-except Block
Syntax:
try:
statement
except:
handling code
Example:
try:
x = 10/0
except ZeroDivisionError:
print("Error occurred")

Multiple except Blocks


except ValueError:
except TypeError:

finally Block
• Executes whether exception occurs or not.
finally:
print("Done")

else Block
• Executes if no exception occurs.
BSDVP ACADEMY
Raising Exception
raise ValueError("Invalid Input")

DATA STRUCTURES – IN-DEPTH NOTES

What is a Data Structure? (Conceptual Depth)


A Data Structure is a systematic way of organizing data in memory to perform operations
like insertion, deletion, searching, and updating efficiently.

Data Structure = Data + Operations + Memory Management


Without proper data structures:
• Programs become slow
• Memory usage increases
• Complex problems become difficult

Why Data Structures are Important?


1. Reduces time complexity
2. Optimizes memory usage
3. Improves program performance
4. Helps in designing algorithms
5. Core foundation for placements & competitive exams

Types of Data Structures (Deep Classification)


A) Based on Data Organization

Linear Data Structures


Data elements are arranged sequentially.
• Each element has a unique predecessor and successor (except first and last).
Examples:
• Array
• Linked List
BSDVP ACADEMY
• Stack
• Queue

Non-Linear Data Structures


Data elements are arranged hierarchically.
• One element can connect to multiple elements.
Examples:
• Tree
• Graph

B) Based on Memory Allocation

Static Data Structure


• Memory allocated at compile time.
• Fixed size.
Example: Array

Dynamic Data Structure


• Memory allocated at runtime.
• Size can grow or shrink.
Example: Linked List

ARRAY (In Depth)

Concept
Array stores elements in contiguous memory locations.
Memory Representation:
If array starts at base address B,
Location of element:
Address = B + (index × size of data type)

This is why array access is O(1)

Advantages
BSDVP ACADEMY
✔ Fast access
✔ Simple implementation
✔ Cache friendly

Disadvantages

✖ Fixed size
✖ Insertion costly
✖ Wastes memory if unused

LINKED LIST (In Depth)

Structure of Node
Each node contains:
• Data
• Pointer (Address of next node)

Why Linked List is Dynamic?


Memory is allocated using dynamic memory allocation.
Nodes are not stored in contiguous memory.

Advantages

✔ Dynamic size
✔ Easy insertion & deletion

Disadvantages

✖ Extra memory for pointer


✖ No direct access (O(n))

STACK (Deep Understanding)

Concept
Stack follows LIFO principle.
BSDVP ACADEMY
Operations happen at only one end (TOP).

Applications
• Function calls (Call Stack)
• Undo/Redo operations
• Expression evaluation
• Parenthesis checking

Implementation
• Using Array
• Using Linked List

QUEUE (Deep Understanding)

Concept
Queue follows FIFO principle.
Insertion → Rear
Deletion → Front

Real Applications
• CPU Scheduling
• Printer queue
• BFS traversal
• Network buffering

TREE (In Depth)

Definition
A Tree is a hierarchical data structure with a root node and subtrees.

Important Properties of Binary Tree


BSDVP ACADEMY
If:
• n = number of nodes
• h = height
Maximum nodes at level L:
= 2^L
Maximum nodes in binary tree of height h:
= 2^(h+1) - 1

Binary Search Tree (BST)


Property:
Left subtree < Root < Right subtree
Search Time:
• Average → O(log n)
• Worst → O(n)

GRAPH (In Depth)

Representation
1. Adjacency Matrix
2. Adjacency List

BFS vs DFS

BFS DFS

Uses Queue Uses Stack

Level-wise Depth-wise

Shortest path Backtracking

Time Complexity (Very Important for Exams)


Common Complexities
BSDVP ACADEMY
Complexity Meaning

O(1) Constant

O(n) Linear

O(log n) Logarithmic

O(n²) Quadratic

O(n log n) Efficient sorting

Searching Algorithms
Linear Search
• Works on unsorted data
• Time → O(n)
Binary Search
• Works only on sorted array
• Time → O(log n)

Sorting Algorithms (Conceptual)


Bubble Sort
Repeatedly swaps adjacent elements.
Merge Sort
Divide and conquer.
Quick Sort
Pivot-based sorting.

Most Important Comparison (High Weightage)


Array vs Linked List

Feature Array Linked List

Memory Contiguous Non-contiguous


BSDVP ACADEMY
Feature Array Linked List

Access O(1) O(n)

Insertion Costly Easy

Size Fixed Dynamic

Stack vs Queue

Stack Queue

LIFO FIFO

One pointer Two pointers

You might also like