History to OOPs & Exception Handling — written by Aivasu Tech Institute's mentors. Free to read, structured to actually help you learn.
Python notes by Aivasu Tech Institute cover 303 topics — from python home to update documents — each explained with short definitions, syntax and runnable code examples. They are 100% free, need no signup, and work as quick revision for college exams, Python interviews and Aivasu Tech Institute's mentor-led Python course in Pitampura, Delhi.
No notes found. Try a different search term, or browse all Python notes.
Python is the most beginner-friendly language for data science, AI and automation, and it is where most Aivasu Tech Institute students start. This free track covers everything from syntax to machine learning.
Python powers websites, data pipelines and AI models, yet reads almost like English. Learn what Python is, where it is used, and why it is the best first language in 2026.
Getting started with Python takes one install and a few lines of code. See how to set up your machine, check the version, and run your very first program.
Python's clean syntax — no braces, no semicolons — is what makes it famous for readability. Learn indentation, comments and the basic rules every script follows.
Statements are the individual instructions Python executes, one line at a time. Understanding how they combine is the foundation for reading any Python program.
Printing output with the print() function is the first step in seeing what your code actually does. It is also how you debug programs for years afterwards.
Numbers print differently from strings, and print() handles both with ease. Learn the differences between displaying digits and text in your output.
Comments explain code to humans and are ignored by Python, making them essential documentation. Good commenting is a habit that pays off in every team project.
Variables store values under a name so you can reuse them throughout a program. They are the most fundamental concept in any programming language.
Variable names follow simple rules — start with a letter or underscore, no spaces or keywords. Choosing clear, descriptive names makes code readable for months to come.
Python lets you assign several variables in one line and unpack collections directly into names. It is a small trick that removes a lot of boilerplate.
Combining variables with text in print() output is a daily task in Python. Learn string concatenation and commas to format messages cleanly.
Global variables live outside functions and are visible everywhere, but they come with traps. Understanding scope here prevents a whole class of hard-to-find bugs.
Every value in Python has a type — int, str, float, bool and more — and types decide what you can do with it. This map of built-in types is your foundation.
Python numbers cover integers, floats and complex values, each with different precision and use. Learn the three numeric types and when each applies.
Casting converts values between types, like turning user input strings into numbers. It is the bridge between what data looks like and what you need it to be.
Strings are sequences of characters, and Python treats them as first-class data. Almost every real program handles text, so string basics matter everywhere.
Slicing pulls out parts of a string using index ranges, from single characters to every other letter. It is one of Python's most elegant and frequently used tricks.
Strings are immutable, but a rich set of methods lets you transform them into new values. Learn upper, lower, strip, replace and friends.
Concatenation joins strings together with the + operator, and f-strings do it even better. Building dynamic messages is a core everyday task.
String formatting inserts values into templates, and modern f-strings make it effortless. Formatting turns data into readable reports and messages.
Escape characters let you include quotes, newlines and tabs inside strings. Without them, some of the simplest text becomes impossible to write.
Python ships with dozens of built-in string methods for searching, splitting and transforming text. Knowing the most useful ones saves writing loops from scratch.
Booleans represent true and false, the outcomes every decision in your program is built on. Learn how comparisons produce them and how they drive logic.
Operators perform calculations, comparisons and logical checks on values. This overview maps arithmetic, comparison, logical and bitwise operators in one place.
Arithmetic operators — add, subtract, multiply, divide and more — turn Python into a calculator. Learn each symbol and the order in which they execute.
Assignment operators store values and update them in one step, like += and *=. They make counter and accumulator code shorter and clearer.
Python's ternary lets you assign one of two values based on a condition in a single line. It is the compact way to express simple either-or logic.
Comparison operators check equality and ordering, producing the booleans that control if statements and loops. They are the grammar of decision-making.
and, or and not combine boolean conditions into complex rules. Getting their precedence right is a classic interview topic and a daily practical need.
is and is not test whether two names point to the exact same object, not just equal values. The distinction matters with lists, None and small integers.
in and not in check whether a value exists inside a collection, like a name in a list. They are the most readable way to test membership in Python.
Bitwise operators work on the individual bits of integers, and they underpin compression, hashing and low-level work. Rare in apps, essential in interviews.
Precedence decides which operation runs first when several appear together, like maths in school. Misreading it is a top source of silent logic bugs.
Lists store ordered, changeable collections of items, and they are Python's most-used data structure. Nearly every script you write will contain one.
Indexing and slicing let you reach any element or sublist by position. Mastering indexes, including negative ones, makes list work second nature.
Lists are mutable, so you can replace items by index or swap ranges in place. This flexibility is what separates lists from tuples.
append, insert and extend grow a list in different ways, each with its own behaviour. Choosing the right one keeps list-building code clean and correct.
Removing items happens with remove, pop, del and clear, and each behaves differently. Knowing what each returns — or fails on — avoids bugs.
Looping over a list processes every item in turn, the core pattern of data handling. for loops over lists appear in almost every Python program.
List comprehensions build new lists from existing ones in a single readable line. They are a signature Python skill that interviewers love to see.
Sorting arranges lists alphabetically or numerically, with reverse and custom key options. It powers leaderboards, rankings and organised output.
Copying a list seems simple until you meet references sharing the same data. Learn shallow copies, deep copies and the list() and copy() methods.
Joining lists combines collections with +, extend or clever comprehensions. It is how datasets get merged before analysis.
Python's list methods cover counting, indexing, reversing and more. A quick tour of the full toolbox keeps you from reinventing built-ins.
Tuples are ordered, immutable collections — like lists that cannot change. They are used for fixed records, function returns and dictionary keys.
Tuple items are reached by index and slice exactly like lists. The difference is that what you read can never be accidentally modified.
Tuples cannot change directly, so updating means building a new tuple or converting through a list. Learn the safe patterns for working around immutability.
Unpacking assigns tuple elements to named variables in one line, including with * for the rest. It makes function returns and data rows elegant to handle.
Iterating over tuples is identical to lists, with the added safety that nothing can change mid-loop. Use for loops to process fixed datasets.
Joining tuples creates a new tuple from existing ones with + and *. It is straightforward once you accept that the original never changes.
Tuples keep a deliberately small API — mostly count and index. Their simplicity is the point, making data integrity the priority.
Sets hold unordered collections of unique items, perfect for membership tests and removing duplicates. They answer what-do-I-have questions instantly.
Sets are unordered, so you cannot index them — but you can loop and test membership. Understanding this changes how you design lookups.
add and update insert items into a set, silently ignoring duplicates. This guarantee of uniqueness is why sets excel at deduplication.
Set removal offers remove, discard and pop, each handling missing items differently. Choosing discard over remove prevents avoidable crashes.
Looping over sets processes each unique item once, in arbitrary order. It is the natural way to act on deduplicated data.
Set operations like union and intersection combine collections using set theory. They solve overlap and difference questions in one line.
A frozenset is an immutable set that can be hashed and used as a dictionary key. It is the version you reach for when the set must never change.
Python's set methods implement union, intersection, difference and more. Knowing them turns messy list comparisons into clean set algebra.
Dictionaries store key-value pairs, giving instant lookups by name — config, JSON, records. They are the most important structure after lists.
Dictionary values are accessed by key, with get() providing safe defaults. Indexing mistakes here are the classic KeyError source.
Dictionaries are mutable, so updating a value or merging updates is a one-liner. Learn assignment and the update method for bulk changes.
Adding dictionary entries is just assigning a new key, and setdefault handles the first-time case. Building lookup tables is a core pattern.
pop, popitem and del remove dictionary entries with different return behaviours. Choosing correctly keeps key-handling code predictable.
Looping over dictionaries can visit keys, values or both using items(). It is how you process records and build reports from mappings.
Copying dictionaries shares the same reference pitfalls as lists, solved with copy() and dict(). Learn to duplicate mappings safely.
Nested dictionaries store dictionaries inside dictionaries, modelling rich structures like users with addresses. JSON data often arrives this way.
The dictionary method toolbox — keys, values, items, update — covers most real-world needs. A quick tour prevents writing loops for built-ins.
if and else choose between code paths based on conditions, the heart of every decision your program makes. This is where programs start behaving intelligently.
elif chains test multiple conditions in order until one passes, replacing nested ifs with readable steps. It is how multi-branch decisions stay tidy.
The else clause catches the case where no condition matched, giving every decision a fallback. Used with if and loops, it completes the logic.
Python's one-line if writes a conditional on a single line for simple cases. Compact, but readability should decide when to use it.
Combining and, or and not inside if conditions builds rich rules from simple checks. Getting the grouping right is where logic bugs hide.
Nested ifs place conditions inside conditions for dependent logic, like checking a login before a role. Keep nesting shallow to stay readable.
pass is a placeholder that does nothing, letting you stub out functions and empty blocks. It keeps incomplete code valid while you build.
match is Python's pattern-matching statement, a cleaner switch-case for comparing structures. It shines with tuples, lists and value patterns.
while loops repeat as long as a condition holds true, powering retries, games and input validation. Beware the infinite loop — control the condition.
for loops iterate over sequences a fixed number of times, and they are Python's workhorse. Combined with range, they cover almost every repetition need.
Functions package reusable logic under a name, taking inputs and returning outputs. They are the basic unit of organised, testable code.
Arguments pass data into functions, by position or by keyword, with defaults available. Getting the argument rules right unlocks flexible APIs.
*args and **kwargs let functions accept any number of extra arguments. They power decorators and wrappers in real Python libraries.
Scope decides where a variable is visible — local, enclosing, global. Misunderstanding it produces the classic unbound variable bugs.
Decorators wrap functions to add behaviour without changing their code, like logging or caching. They are a professional-level tool you meet in real projects.
Lambda functions are small anonymous functions written inline, ideal for one-off logic like sorting keys. Use them where a full def would be noise.
Recursion is a function calling itself to break problems into smaller copies, from factorials to tree traversal. It trades elegance for careful base cases.
Generators produce values one at a time with yield instead of building a whole list. They keep memory tiny when processing huge or infinite sequences.
range() generates sequences of numbers for loops without creating a list. It is the standard way to repeat code a fixed number of times.
Python lists cover most needs, but the array module stores typed values compactly. It matters when memory and raw performance count.
Iterators are objects you can loop over, and iter() and next() drive them manually. Understanding them explains how for loops really work.
Modules are files of reusable code you import into any program. The standard library is a toolbox of modules you already own.
The datetime module handles dates and times — creating, formatting and calculating them. Almost every business application stores timestamps.
Python's math module provides square roots, trigonometry, logs and constants. It turns Python into a scientific calculator.
JSON is the data format of the web, and Python converts it to dictionaries and back with one line. Parsing JSON is a daily job for backend and data roles.
Regular expressions search and extract patterns in text, from phone numbers to emails. They are dense but worth it — interviewers love them.
pip installs packages from PyPI, opening up thousands of libraries. Managing packages is a fundamental skill for any real Python project.
try and except catch runtime errors so your program can respond instead of crashing. Handling errors gracefully is what production code does.
Python offers several string formatting styles, with f-strings as the modern favourite. Formatting numbers and text well polishes every program.
None is Python's way of saying no value, and it appears everywhere — empty results, defaults, missing data. Learn to check for it safely.
input() reads what the user types, always returning a string. Converting and validating that input is where real programs begin.
Virtual environments isolate each project's packages so dependencies never clash. Every professional Python workflow starts with one.
Object-oriented programming organises code into classes and objects that bundle data with behaviour. It is the dominant style in large Python systems.
Classes are blueprints and objects are instances created from them. This topic builds the mental model behind all of OOP.
__init__ runs when an object is created, setting up its attributes. It is the constructor that every well-designed class defines.
self refers to the current object inside a class, linking methods to their data. It is the first parameter of every instance method.
Properties in classes control how attributes are read and written, adding validation without changing the interface. They make data access safe.
Class methods receive the class itself and build alternate constructors or shared state. They sit between instance methods and statics.
Inheritance lets a child class reuse and extend a parent's behaviour. It is how frameworks build hierarchies you plug into.
Polymorphism lets different classes respond to the same method name in their own way. It is what makes code generic and interchangeable.
Encapsulation hides internal details behind public methods, protecting data from misuse. It is the discipline that keeps large codebases maintainable.
Inner classes are defined inside another class, useful for tightly related helpers. They are a niche pattern with specific use cases.
File handling reads and writes files on disk — logs, CSVs, reports. The open() function and context managers make it safe and simple.
Reading files gives you their contents as strings or lists of lines. Learn the modes and the with statement that prevents leaks.
Writing files creates or overwrites them, with append mode to add. Understanding each mode protects you from destroying data.
Deleting files uses the os module, and the same module checks existence first. Filesystem operations deserve a cautious hand.
Matplotlib is Python's original plotting library, turning data into charts. It is the foundation most data visualisation tools build on.
Installing and importing matplotlib is the first step to your first chart. Learn the setup that every plotting project starts with.
pyplot is matplotlib's simple interface where a few lines produce a plot. It is the fast path from data to a chart on screen.
plot() draws points and lines from x and y values, the simplest visualisation there is. Customising markers and styles follows naturally.
Markers style the points on a plot — circles, stars, crosses — making trends readable. They distinguish data series at a glance.
Line styles and colours turn basic lines into clear comparisons between datasets. Small style choices carry the story of the data.
Labels, titles and gridlines tell viewers what a chart actually shows. A chart without labels is just decoration.
Gridlines add reference lines to a plot so values can be read precisely. They make professional-looking charts with one call.
Subplots arrange multiple charts in one figure for side-by-side comparison. They are how dashboards show several metrics together.
Scatter plots place individual points to reveal relationships between two variables. They are the classic first look at correlation.
Bar charts compare categories with vertical or horizontal bars. They are the most common chart in business reporting.
Histograms show how values are distributed across ranges, revealing shape and outliers. They are essential for understanding any dataset.
Pie charts show proportions of a whole as slices, though experts use them sparingly. Learn them — and when a bar chart works better.
This topic sets up the data science workflow in Python, from imports to data loading. A solid setup routine saves hours later.
Mean, median and mode summarise the centre of a dataset in three different ways. They are the first statistics every analyst computes.
Standard deviation measures how spread out values are around the mean. It quantifies uncertainty and variation in one number.
Percentiles tell you where a value stands in a distribution — the median is the 50th percentile. They power grades, rankings and benchmarks.
Understanding how data is distributed guides every later decision, from models to visualisations. This topic introduces the distributions you will meet.
The normal distribution — the bell curve — describes countless natural datasets. It underpins much of statistics and machine learning.
Scatter plots in analysis reveal correlation, clusters and outliers between variables. They are your first visual tool for relationships.
Linear regression fits a straight line through data to predict outcomes from one variable. It is the entry point to predictive modelling.
Polynomial regression fits curves instead of straight lines when relationships bend. It extends linear regression to non-linear trends.
Multiple regression predicts an outcome from several variables at once. It is how real-world models account for many factors.
Scaling standardises features onto a common range so models compare them fairly. Without it, large numbers can dominate your model.
Splitting data into train and test sets lets you measure how a model performs on unseen data. It is the core discipline of machine learning.
Decision trees split data on questions, forming a flowchart-like model that is easy to explain. They are both powerful and interpretable.
The confusion matrix tabulates predictions against actuals, exposing where a classifier succeeds and fails. It is the honest scorecard of classification.
Hierarchical clustering groups similar items into a tree of clusters. It reveals structure in data without needing a target column.
Logistic regression predicts probabilities for yes/no outcomes despite its name. It is the workhorse of binary classification.
Grid search tests combinations of hyperparameters to find the best model settings. It automates the tedious tuning loop.
Categorical data — colours, cities, labels — needs special handling before models can use it. Encoding turns words into numbers.
K-means partitions data into k clusters by similarity, unsupervised. It is the most widely used clustering algorithm.
Bootstrap aggregation, or bagging, trains many models on resampled data and averages them. It is the idea behind Random Forest.
Cross-validation rotates the data into different train/test folds so your score is reliable. It prevents fooling yourself with lucky splits.
The ROC curve and its AUC score measure a classifier's ability to separate classes. It is the standard metric in many competitions.
K-nearest neighbours classifies a point by the labels of its closest neighbours. Simple, intuitive and surprisingly effective.
Data structures and algorithms are the interview currency of software engineering, and Python makes them approachable. This section builds DSA intuition.
Lists and arrays store ordered data, and understanding their costs decides how fast your programs run. This topic grounds DSA in Python's reality.
Stacks follow last-in-first-out order, like a pile of plates, and they power undo features and expression evaluation. Push and pop are the whole story.
Queues are first-in-first-out structures like a ticket line, used in scheduling and message systems. Learn enqueue, dequeue and their uses.
Linked lists chain nodes with pointers instead of using contiguous memory. They trade random access for cheap insertions and deletions.
Hash tables map keys to values with near-instant lookups, the idea behind Python dictionaries. They are the fastest structure for membership.
Trees organise data in parent-child hierarchies, from file systems to organisation charts. They are the structure behind search and AI algorithms.
Binary trees give each node up to two children, the foundation of expression evaluation and hierarchical storage. Traversal is the key skill.
Binary search trees keep values ordered so lookups take logarithmic time. Balancing them keeps performance from degrading.
AVL trees are self-balancing binary search trees that guarantee efficient operations. They show how structure design prevents worst cases.
Graphs model networks — social, transport, dependency — as nodes and edges. They are the richest and most asked-about DSA topic.
Linear search checks each element in turn until it finds the target. Simple and honest, it is the baseline every other search beats.
Binary search halves the search space each step, finding items in sorted data at logarithmic speed. It is the interview favourite for a reason.
Bubble sort swaps neighbouring elements until the list is ordered, teaching the mechanics of sorting. Slow, but a perfect first algorithm.
Selection sort repeatedly picks the smallest remaining element. Its fixed number of comparisons makes it a clean teaching example.
Insertion sort builds the sorted list one element at a time, the way you sort playing cards. It shines on small or nearly sorted data.
Quick sort partitions around a pivot and recurses, averaging the fastest comparison sort. It is the default sort in many real libraries.
Counting sort sorts by tallying values, running in linear time for small integer ranges. It shows that non-comparison sorts can break the usual limits.
Radix sort orders numbers digit by digit using stable counting passes. It handles huge datasets where comparison sorts stall.
Merge sort splits, sorts halves and merges them back, guaranteeing efficient order on every input. Its stability matters in real systems.
This section shows Python working with MySQL, the classic combination for web backends. Connect, query and manage data from code.
Creating a MySQL database from Python is the first backend task — a single command through the driver. It is the setup for everything after.
Defining tables from Python mirrors SQL's CREATE TABLE with the driver's API. Schemas built in code travel with your project.
Inserting rows from Python binds application data into MySQL with parameterised queries. It is the write path of every CRUD app.
Selecting from MySQL in Python returns rows you can loop through and transform. It is the read path behind dynamic pages.
Adding WHERE filters to Python queries returns only matching rows, keeping transfers small. Parameter placeholders keep it secure.
Ordering results from Python lets the database sort before data arrives. It saves re-sorting large result sets in code.
Deleting rows through Python is the dangerous write operation, so filters are non-negotiable. The same caution as SQL applies in code.
Dropping tables from Python removes schemas programmatically during migrations and teardown. It is a deliberate, careful operation.
Updating records from Python changes stored data with application logic. WHERE clauses protect the rows you did not mean to touch.
LIMIT in Python queries caps how many rows return, essential for pagination and previews. It keeps APIs fast on large tables.
Joining tables from Python combines related data — orders with customers — before it reaches your code. The same join logic, driven from Python.
Python with MongoDB pairs the language with a document database, no tables required. Learn the driver that stores dictionaries directly.
MongoDB creates databases and collections lazily on first use, unlike SQL. Understanding this model changes how you plan storage.
Collections hold documents the way tables hold rows, but without a fixed schema. Each document can carry different fields.
Inserting documents into MongoDB stores Python-style dictionaries directly. It is the friction-free write path of document databases.
find() queries MongoDB with filter dictionaries, returning matching documents. The syntax maps directly onto Python dicts.
Querying MongoDB builds filters with operators like $gt and $in. This query language is JSON-like and deeply composable.
Sorting MongoDB results uses the sort() method with field and direction. It mirrors ORDER BY for document collections.
Deleting documents in MongoDB uses delete_one and delete_many with filters. Precision matters just as much as in SQL.
Dropping a collection removes all its documents and structure at once. It is the document-database equivalent of DROP TABLE.
Updating MongoDB documents uses update_one and update_many with modifiers like $set. It evolves records without full rewrites.
LIMIT in MongoDB queries caps returned documents for pagination and sampling. Small result sets keep applications responsive.
Where Python came from — who created it, why it was named after Monty Python, and how it became the world's most popular language.
Learn how Python variables work and explore its core data types — int, float, str, bool, list, tuple, set, and dict.
Learn Python's arithmetic, comparison, logical, assignment, membership, and bitwise operators with practical examples.
Master conditional logic in Python — if, elif, else, nested conditions, and the ternary expression.
Master the for loop and while loop in Python, plus break, continue, and nested loops with practical examples.
Learn how to define reusable blocks of code with def, parameters, return values, and default arguments.
Understand Python lists — ordered, mutable collections — with indexing, slicing, and common list methods.
Learn about tuples — Python's immutable, ordered collections — and when to use them over lists.
Explore Python sets — unordered collections of unique items — and operations like union and intersection.
Master Python dictionaries — key-value pairs for fast lookups — with methods to add, update, and access data.
Learn Object-Oriented Programming in Python — classes, objects, inheritance, encapsulation, and polymorphism.
Learn how to read, write, and manage files in Python using open(), read(), write(), and context managers.
Master regular expressions in Python using the re module to search, match, and manipulate text patterns.
Learn how to handle errors gracefully in Python using try, except, finally, and custom exceptions.
What Python is, why it is popular, and the kinds of problems it is used for.
Installing Python and running your first program.
The building blocks of a Python program.
Why whitespace matters and how blocks are defined without braces.
Converting between types with int(), float() and str().
The format() method and modern formatting options.
Running code when a condition is true.
A placeholder that does nothing.
Structural pattern matching introduced in modern Python.
Generating number sequences for loops.
Running a block after a loop completes.
Controlling loop execution.
Passing values into functions.
Accepting flexible positional and keyword arguments.
Small anonymous functions.
Isolating project dependencies.
Pattern matching with the re module.
Reading input from the user.
Running cleanup code no matter what.
Throwing errors deliberately.
Reading text and binary files.
Creating and saving files.
Removing files and folders.
Blueprints and the instances they create.
Setting up a new object.
Referring to the current instance.
Attributes and the property decorator.
Methods bound to the class or instance.
A class defined inside another class.
Adding, updating and removing array items.
The foundation library for numerical computing.
Installing and importing NumPy.
Building arrays from data.
Selecting elements from arrays.
Extracting ranges from arrays.
The dtypes NumPy supports.
How array data is shared or duplicated.
Changing the dimensions of an array.
Looping over array contents.
Combining and breaking apart arrays.
Finding and ordering values.
Selecting elements by condition.
Generating random data.
Vectorised operations with ufuncs.
The go-to library for tabular data.
Installing and importing Pandas.
One-dimensional labelled data.
Two-dimensional tables of data.
Loading data from CSV files.
Loading data from JSON.
Inspecting and summarising data.
Fixing messy datasets.
Dealing with missing values.
Correcting types and outliers.
Deduplicating rows.
Measuring relationships between columns.
The core plotting library for Python.
The simple plotting interface.
Drawing your first line chart.
Colours, styles and line formats.
Point markers on plots.
Plotting continuous data.
Annotating axes and charts.
Adding reference lines.
Multiple plots in one figure.
Plotting relationships between points.
Comparing categories.
Showing distributions.
Displaying proportions.
The workflow behind a machine learning project.
Measures of central tendency.
The bell curve and why it matters.
Normalising features.
Splitting data to evaluate models.
Encoding non-numeric features.
Why data structures and algorithms matter.
Defining tables programmatically.
Adding rows safely.
Reading data back.
Filtering results.
Sorting query output.
Removing rows.
Deleting tables.
Changing existing rows.
Restricting result size.
Creating a MongoDB database.
Making collections.
Adding records.
Querying data.
Selecting documents by condition.
Ordering results.
Removing records.
Deleting a collection.
Modifying records.
Join Aivasu Tech Institute's Python course — live mentorship, hands-on projects, and 100% placement support in Delhi NCR.
Enroll Now — Free Demo Available✳ Common questions
What students search before reading Python notes.