Tuesday, 18 August 2026

97 Things Every Programmer Should Know: Collective Wisdom from the Experts (Free PDF)

97 Things Every Programmer Should Know: Collective Wisdom from the Experts

Programming is often taught through syntax, algorithms, frameworks, and projects. But becoming a truly good programmer requires much more than knowing how to write code. It requires learning how to think about software, communicate with users and teammates, test ideas, maintain existing systems, choose appropriate tools, and continuously improve your engineering practices.

97 Things Every Programmer Should Know: Collective Wisdom from the Experts, edited by Kevlin Henney, is a collection of short essays that explores these broader aspects of professional programming. Published by O'Reilly in 2010, the book contains 97 contributions from experienced programmers and software practitioners. The O'Reilly edition is listed as 255 pages, while the ebook edition is listed at 258 pages.

The book is deliberately different from a traditional programming textbook. It does not teach one programming language or framework. Instead, it presents practical advice and principles that can be applied across programming languages, projects, teams, and technologies.

Download the PDF for free:

  97 Things Every Programmer Should Know: Collective Wisdom from the Experts (Free PDF)

What Is the Book About?

The central idea behind the book is simple: good programming is a craft.

Knowing syntax is only the beginning. A programmer also needs to understand how software behaves over time, how code affects other developers, how users interact with applications, and how seemingly small technical decisions can create long-term consequences.

The 97 essays cover topics such as:

  • Code quality

  • Simplicity

  • Testing

  • Refactoring

  • Software design

  • APIs

  • Databases

  • Algorithms

  • Data structures

  • Version control

  • Continuous learning

  • Debugging

  • Automation

  • User experience

  • Team collaboration

  • Professional development

The official contents include topics such as "Code Is Design," "Code Reviews," "Continuous Learning," "Deploy Early and Often," "Don't Repeat Yourself," "Improve Code by Removing It," "Put Everything Under Version Control," "Read Code," "The Single Responsibility Principle," and "Use the Right Algorithm and Data Structure."

Why This Book Is Different from a Programming Textbook

A conventional programming book may teach you:

def calculate_total(price, tax):
    return price + price * tax

But knowing how to write this function does not answer larger engineering questions.

Should the function be this small?

Should the tax calculation be separated?

How should the function be tested?

What happens if the input is invalid?

Will another developer understand the function six months later?

Should the function name reflect business terminology?

Should the behavior be documented?

These are the kinds of questions that distinguish writing code from engineering software.

That is where this book becomes useful.

The Book Is About Programming Beyond Syntax

One of the strongest themes throughout the collection is that programming is not simply about making a computer execute instructions.

Software exists to solve problems.

That means programmers need to understand:

Users

Business requirements

Domain concepts

System constraints

Technical trade-offs

Maintenance

Team communication

The book's essays encourage programmers to think about all of these dimensions rather than focusing exclusively on implementation.

Code Is Design

One of the important topics in the book is the idea that code itself represents design.

Design is sometimes treated as something that happens before programming begins.

In reality, implementation decisions continuously shape the architecture of a software system.

Choosing:

  • A class structure

  • A function boundary

  • An API

  • A database model

  • An abstraction

  • A module structure

is also a design decision.

This means developers should not think of coding as simply translating an already-finished design into syntax.

The code is part of the design.

Why This Matters

Poorly designed code can make future changes difficult.

For example, imagine a Python application where one enormous function handles:

  • User authentication

  • Database operations

  • Email notifications

  • Payment processing

  • Report generation

Even if the program works, maintaining it will become increasingly difficult.

Breaking responsibilities into meaningful components can make the system easier to understand and modify.

This is why software design and code quality are deeply connected.

Beauty Is in Simplicity

Another recurring lesson is the value of simplicity.

Programmers sometimes create complicated solutions because complicated solutions appear more sophisticated.

But complexity has a cost.

Every unnecessary abstraction can increase:

  • Maintenance effort

  • Cognitive load

  • Debugging difficulty

  • Testing requirements

  • Onboarding time

A simpler solution is often easier to understand and change.

This does not mean that every program should be simplistic.

The goal is appropriate simplicity.

A good programmer learns to distinguish between complexity that is necessary and complexity that exists only because of poor design.

The Boy Scout Rule

One of the well-known ideas associated with the book is the Boy Scout Rule.

The principle is commonly summarized as leaving the code in a slightly better condition than you found it.

Imagine opening an old function and noticing:

  • A confusing variable name

  • Unnecessary duplication

  • Poor formatting

  • An outdated comment

Instead of ignoring everything because "it was already like that," a developer can make a small improvement while working in the area.

Over time, many small improvements can significantly improve a codebase.

This is particularly useful in large and long-lived projects.

Why Small Improvements Matter

Software quality rarely improves through one gigantic cleanup operation.

Large refactoring projects can be risky and expensive.

Small, continuous improvements are often easier to review and integrate.

The idea is:

Touch code → Understand it → Improve it → Leave it cleaner

This creates a culture of continuous improvement.

Don't Repeat Yourself

The book also includes the familiar principle Don't Repeat Yourself, commonly known as DRY.

The fundamental idea is that duplicated knowledge creates maintenance problems.

Consider:

price = quantity * unit_price

If the same business rule is duplicated across ten different locations, changing that rule later becomes difficult.

However, DRY should not be interpreted as "never write similar-looking code."

Two pieces of code may look similar while representing different business concepts.

The deeper lesson is to avoid duplicating knowledge and responsibility, not simply identical lines of syntax.

Testing Is a Core Engineering Practice

Testing receives substantial attention throughout the book.

The contents include topics such as:

  • Testers Are Your Friends

  • Test for Required Behavior Not Incidental Behavior

  • Test Precisely and Concretely

  • Testing Is the Engineering Rigor of Software Development

  • Write Tests for People

Testing is not merely about checking whether a program currently works.

Good tests can also communicate what the software is supposed to do.

For example:

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

A test such as:

assert add(2, 3) == 5

does more than verify a calculation.

It also communicates expected behavior.

Testing as Documentation

Well-designed tests can act as executable documentation.

A developer reading:

assert calculate_discount(100, 10) == 90

can immediately understand one expected behavior of the function.

This is particularly useful when requirements are complicated or when the original developer is no longer working on the project.

Code Reviews

Code review is another important software-engineering practice represented in the book.

A code review provides an opportunity for another developer to examine changes before they become part of the system.

Reviewers may identify:

  • Bugs

  • Security issues

  • Poor naming

  • Duplicated logic

  • Architectural problems

  • Missing tests

  • Unnecessary complexity

But effective code reviews should not become competitions about who knows more.

The objective is to improve the software.

A Good Code Review Culture

A healthy review process focuses on questions such as:

Does the code solve the problem?

Is the design understandable?

Is it tested?

Could it introduce a regression?

Will future developers be able to maintain it?

This creates a collaborative engineering environment rather than a personal criticism system.

Continuous Learning

Technology changes rapidly.

Programming languages evolve.

Frameworks become obsolete.

New architectures emerge.

Development tools improve.

The book includes Continuous Learning among its topics, reinforcing the idea that professional programmers need to keep developing their knowledge.

Continuous learning does not necessarily mean learning every new framework.

Instead, programmers should develop durable fundamentals while selectively learning technologies that are relevant to their work.

For example, a Python developer might focus on:

Python → APIs → Databases → Testing → Git → Cloud → AI/ML

rather than attempting to learn every programming language available.

Learn More Than One Language

The book also contains Know Well More Than Two Programming Languages.

Learning multiple languages can expose developers to different programming paradigms and ways of thinking.

For example:

Python emphasizes readability and flexibility.

JavaScript provides a strong foundation for web development.

Java emphasizes object-oriented and enterprise programming.

C provides insight into lower-level programming and memory.

Functional languages can introduce different approaches to state and computation.

The objective is not to collect programming languages as trophies.

The objective is to expand your understanding of programming itself.

Know the Language's Culture

Learning syntax is not enough.

Every programming language has its own ecosystem, conventions, idioms, tools, and community practices.

For example, Python programmers commonly value readability and idiomatic simplicity.

A programmer who knows Python syntax but ignores Python conventions may still write technically valid code that feels unnatural to experienced Python developers.

Understanding a language's culture therefore becomes part of becoming proficient in that language.

Choose Your Tools with Care

Modern developers have access to thousands of tools.

Editors, IDEs, libraries, frameworks, databases, cloud services, testing tools, CI/CD platforms, containers, and AI assistants can all improve productivity.

But tools should solve problems rather than create unnecessary complexity.

A good question is not:

"What is the newest tool?"

Instead:

"What problem am I trying to solve?"

This prevents technology choices from becoming driven purely by trends.

Know Your IDE and Command-Line Tools

The book also emphasizes practical development skills such as knowing your IDE and command-line tools.

This may seem less exciting than learning a new framework, but productivity often depends heavily on how efficiently a developer can navigate their development environment.

Understanding features such as:

  • Debugging

  • Search

  • Refactoring

  • Navigation

  • Code inspection

  • Version-control integration

  • Terminal commands

can save enormous amounts of time.

Automation

The book repeatedly highlights automation.

Automation can remove repetitive manual work from development workflows.

For example:

Manual testing

→ Run tests one by one

versus

Automated testing

→ Run the entire test suite automatically

Similarly:

Manual deployment

→ Developer performs deployment steps

versus

Automated CI/CD

→ Pipeline builds, tests, and deploys automatically

Automation allows developers to spend more time solving meaningful problems.

Deploy Early and Often

The book includes the principle Deploy Early and Often.

This challenges the idea that software should remain hidden until everything is perfect.

Early deployment can reveal:

  • Integration problems

  • Performance issues

  • User misunderstandings

  • Infrastructure limitations

  • Unexpected edge cases

The earlier these problems become visible, the less expensive they can be to fix.

This principle connects naturally with modern practices such as:

  • Continuous Integration

  • Continuous Delivery

  • Continuous Deployment

  • Automated Testing

Put Everything Under Version Control

Version control is one of the most fundamental practices in software development.

A version-control system allows developers to track changes and collaborate safely.

Git is now widely used for this purpose.

A simple workflow might look like:

Create branch
     ↓
Make changes
     ↓
Run tests
     ↓
Commit
     ↓
Push
     ↓
Code review
     ↓
Merge

Version control also provides historical information.

If something breaks, developers can investigate what changed.

Without version control, tracking the evolution of a project becomes much harder.

Read Code

Writing code is only part of a programmer's job.

Developers spend substantial amounts of time reading:

  • Existing applications

  • Libraries

  • APIs

  • Documentation

  • Pull requests

  • Logs

  • Tests

  • Configuration files

The book includes Read Code as a dedicated topic.

Learning to read unfamiliar code is therefore a critical programming skill.

Why Reading Code Is Difficult

Writing new code gives you control over the structure.

Reading existing code means entering someone else's mental model.

You need to determine:

What does this code do?

Why was it written this way?

What assumptions does it make?

What depends on it?

What could break if I change it?

These questions are central to maintenance and debugging.

Improve Code by Removing It

More code does not necessarily mean better software.

Every additional line creates another opportunity for:

  • Bugs

  • Complexity

  • Maintenance

  • Testing

  • Misunderstanding

Sometimes the best improvement is removing unnecessary code.

For example, if a complicated implementation can be replaced with a simpler standard-library function, the resulting system may be easier to maintain.

This is an important mindset shift:

Programming is not about maximizing the amount of code you write.

It is about creating the simplest reliable solution to the problem.

Use the Right Algorithm and Data Structure

Performance often depends more on the algorithm and data structure than on small code-level optimizations.

For example, searching for an item in a list generally requires different work from checking membership in a set.

Conceptually:

items = [1, 2, 3, 4, 5]

and:

items = {1, 2, 3, 4, 5}

represent different data structures with different characteristics.

Understanding:

  • Arrays

  • Lists

  • Sets

  • Dictionaries

  • Trees

  • Graphs

  • Queues

  • Stacks

helps developers choose appropriate solutions.

The book explicitly includes Use the Right Algorithm and Data Structure among its 97 topics.

Comments Should Add Meaning

The book also discusses comments and emphasizes that comments should explain things that the code itself cannot communicate clearly.

Consider:

# Add 1 to count
count += 1

This comment adds little value because the code already communicates the operation.

A more useful comment might explain why something unusual is being done.

For example:

# API returns timestamps in UTC, so convert before comparison.

The code may not make that business or technical assumption obvious.

This leads to a useful rule:

Use code to explain what. Use comments to explain why.

Think About the User

One of the book's listed topics asks:

"What Would the User Do?" — You Are Not the User.

Developers naturally understand their own software differently from first-time users.

A developer may know exactly where a feature is located.

A new user does not.

Therefore, assumptions based on the developer's own behavior can be misleading.

Good software development requires observing actual users and understanding their workflows.

This is especially important for:

  • Web applications

  • Mobile applications

  • SaaS products

  • Forms

  • Dashboards

  • APIs

  • Developer tools

Code Is Written for the Future

One of the most practical lessons in the book is the importance of writing code that other people can understand and maintain.

The book includes:

Write Code As If You Had to Support It for the Rest of Your Life

This is a powerful mindset.

Instead of asking:

"Can I make this work?"

ask:

"Will someone else understand this six months from now?"

That changes programming decisions.

You start paying greater attention to:

  • Naming

  • Structure

  • Tests

  • Documentation

  • Error handling

  • Simplicity

  • Dependencies

Professional Programming

The book also includes The Professional Programmer as one of its topics.

Professionalism in software development is not simply about technical ability.

It also involves:

  • Taking responsibility

  • Communicating clearly

  • Meeting commitments

  • Learning from mistakes

  • Respecting teammates

  • Writing maintainable software

  • Understanding business requirements

  • Thinking about users

A programmer can write highly optimized code and still be ineffective if they cannot collaborate with others.

Who Should Read This Book?

Beginners

Beginners can use the book to develop good habits early.

However, it works best when read alongside actual programming practice.

Intermediate Programmers

Intermediate developers may get even more value because they already have enough experience to recognize the problems discussed in the essays.

Experienced Developers

Senior developers can use the essays as reminders and discussion starters.

Some ideas may feel familiar, but revisiting familiar principles from a different perspective can still be useful.

Software Engineering Students

Students can use the book to complement technical courses on programming languages, algorithms, databases, and software engineering.

Developers Switching Languages

Because the advice is largely language-independent, the book is useful when moving between programming ecosystems.

How to Read the Book

You do not necessarily need to read all 97 essays in order.

Because the chapters are short and relatively independent, the book works well as a reference.

For example, if you are currently struggling with testing, you can focus on the testing-related essays.

If you're working on a large legacy project, read the chapters about refactoring, code quality, version control, and maintenance.

If you're beginning your career, start with:

Continuous Learning

Read Code

The Professional Programmer

Code Reviews

Testing

Simplicity

This makes the book useful both as a linear read and as a professional reference.

Key Lessons for Modern Programmers

Although the book was published in 2010, many of its principles remain relevant because they concern fundamental software-engineering practices rather than temporary technologies.

Here are some of the most valuable lessons:

Write Less, Better Code

More code creates more maintenance.

Prefer Simplicity

Simple systems are generally easier to understand and change.

Test Behavior

Tests should verify what the software is supposed to accomplish.

Read Existing Code

Professional development involves much more reading than beginners expect.

Keep Learning

Programming is a constantly evolving profession.

Automate Repetitive Work

Computers are excellent at repetitive tasks.

Use Version Control

Track changes and make collaboration safer.

Think About Users

Developers are not automatically representative of users.

Choose Appropriate Abstractions

Abstraction should reduce complexity, not hide it behind unnecessary layers.

Treat Code as a Long-Term Asset

The code you write today may need to be maintained by someone else years later.

Is the Book Still Relevant?

Yes, particularly at the level of software-engineering principles.

The book does not teach modern frameworks such as React, FastAPI, PyTorch, Kubernetes, or today's generative-AI tooling. Those technologies have changed significantly since the book's publication.

But concepts such as:

  • Testing

  • Simplicity

  • Code review

  • Version control

  • Refactoring

  • Automation

  • Domain understanding

  • Good APIs

  • Appropriate algorithms

  • Continuous learning

remain fundamental.

The O'Reilly catalog still presents the book as a beginner-level programming title, and its table of contents continues to emphasize these language-independent engineering principles.

Hard Copy:  97 Things Every Programmer Should Know: Collective Wisdom from the Experts

Kindle: 97 Things Every Programmer Should Know: Collective Wisdom from the Experts

Download the PDF for free:

 https://github.com/Babunashvili/Books-To-Read-Before-You-Die/blob/master/Ebooks/97%20Things%20Every%20Programmer%20Should%20Know%20-%20%5BHenney%5D.pdf

Final Verdict

97 Things Every Programmer Should Know is not a book about learning Python, Java, C++, JavaScript, or any other specific programming language.

It is a book about becoming a better software developer.

Its greatest strength is its variety. Ninety-seven short contributions provide different perspectives on programming, software design, testing, debugging, collaboration, tools, maintenance, and professional growth. The contributors include experienced practitioners such as Michael Feathers, Pete Goodliffe, Diomidis Spinellis, Cay Horstmann, and Verity Stob.

Some chapters may feel obvious to experienced developers. Others may challenge assumptions or provide a new way of thinking about familiar problems. That variety is part of the book's appeal.

The most important takeaway is that programming is not simply about making code run.


Python Coding Challenge - Question with Answer (ID 180826)



Explanation:

Code
print(True << 3 | False)

Heading: Step 1 — True as an Integer

In Python, Boolean values behave like integers in arithmetic and bitwise operations:

True = 1
False = 0

So the expression becomes:

1 << 3 | 0

Heading: Step 2 — Left Shift <<
1 << 3

The << operator shifts the binary bits 3 positions to the left.

Binary representation:

1  →  0001

After shifting 3 positions:

0001 << 3
1000

Binary 1000 is decimal 8.

Therefore:

1 << 3

gives:

8

Heading: Step 3 — Bitwise OR |

Now we have:

8 | 0

Binary:

8 → 1000
0 → 0000

Bitwise OR gives 1 whenever at least one corresponding bit is 1:

1000
0000
----
1000

1000 in binary is 8.

Heading: Step 4 — Final Output

Therefore:

print(True << 3 | False)

produces:

8

Final Answer

Output: 8

Book: 100 Python Challenges to Think Like a Developer

Monday, 17 August 2026

Python Coding Challenge - Question with Answer (ID 170826)

 


Explanation:

1. Code
print(True + True * 2)
\
2. True as an Integer

In Python, bool is a subclass of int.

So Python treats:

True

as:

1

Therefore:

True = 1

3. True * 2

First, Python evaluates the multiplication:

True * 2

Since True is 1:

1 × 2 = 2

So:

True * 2

becomes:

2

4. True + 2

Now the expression becomes:

1 + 2

Therefore:

3

5. Operator Precedence

Python performs multiplication before addition.

So:

True + True * 2

is evaluated as:

True + (True * 2)

not:

(True + True) * 2

6. print()

Finally:

print(3)

displays the result.

✅ Final Output
3

Book: 100 Python Automation Projects for Smart Developers

Sunday, 16 August 2026

Pen and Paper Exercises in Machine Learning(Free PDF)

 




Machine learning is often learned through Python, notebooks, datasets, and ready-made libraries. While practical implementation is extremely important, there is another side of machine learning that is sometimes overlooked: mathematical reasoning.

Pen and Paper Exercises in Machine Learning, written by Michael U. Gutmann, takes a different approach. Instead of concentrating primarily on programming, it provides a collection of mostly pen-and-paper exercises designed to strengthen the mathematical understanding behind machine-learning methods.

The work was submitted to arXiv in June 2022 and covers topics including linear algebra, optimization, graphical models, message passing, hidden Markov models, model-based learning, sampling, Monte Carlo integration, and variational inference.

The main idea is simple: sometimes the best way to understand a machine-learning algorithm is to work through its reasoning by hand.


Download the PDF for free:
 Pen and Paper Exercises in Machine Learning

Why Pen-and-Paper Learning Matters

Modern machine-learning libraries can perform complicated calculations almost instantly.

A few lines of Python can train a model, calculate gradients, perform optimization, or make predictions. This is extremely useful, but it can also hide the reasoning behind the algorithm.

When students solve a problem manually, they are forced to understand:

  • What the algorithm is actually doing

  • Why each step is necessary

  • How different mathematical concepts connect

  • Where assumptions are being made

  • How the final result is obtained

  • Why an algorithm behaves differently under different conditions

The exercises in this work are designed around this type of deeper understanding. The author specifically explains that the exercises are intended to strengthen mathematical skills and complement, rather than replace, machine-learning courses or textbooks.


The Mathematical Side of Machine Learning

Machine learning is not only a programming discipline. It combines several areas of mathematics and statistics.

A machine-learning student may encounter:

  • Linear algebra

  • Calculus

  • Probability

  • Statistics

  • Optimization

  • Graph theory

  • Numerical methods

  • Information theory

These subjects are not isolated from machine learning. They provide the tools used to design models, understand data, perform inference, and optimize algorithms.

This is why mathematical exercises can be extremely valuable for someone studying machine learning at an advanced level.


Linear Algebra

The first major topic covered is linear algebra.

Linear algebra forms the foundation of many machine-learning algorithms because data and model parameters are frequently represented using vectors and matrices.

The exercises explore concepts such as:

  • Gram–Schmidt orthogonalization

  • Linear transformations

  • Eigenvalue decomposition

  • Symmetric matrices

  • Trace

  • Determinants

  • The power method

These concepts are important in many areas of machine learning, including dimensionality reduction, optimization, numerical computation, and representation learning.

Why Linear Algebra Matters

A strong understanding of linear algebra allows learners to understand what machine-learning software is actually calculating.

Instead of treating matrix operations as mysterious commands inside a programming library, students can understand their geometric and computational meaning.

This becomes particularly important when studying algorithms such as PCA, graphical models, neural networks, and optimization methods.


Optimization

Optimization is another fundamental part of machine learning.

A machine-learning model generally has some objective that it wants to improve. Training involves searching for parameter values that provide better results according to that objective.

The optimization section helps readers develop the mathematical reasoning required to understand this process.

Important concepts include:

  • Gradients

  • Optimization objectives

  • Gradient-based methods

  • Local behavior of functions

  • Parameter updates

  • Convergence

  • Optimization challenges

Optimization is particularly important because many machine-learning algorithms are essentially optimization procedures wrapped around statistical or mathematical models.


Graphical Models

One of the strongest themes of the collection is probabilistic graphical models.

Graphical models provide a visual and mathematical framework for representing relationships between variables.

They can help describe:

  • Dependencies

  • Conditional independence

  • Probabilistic relationships

  • Hidden variables

  • Inference problems

  • Structured data

The collection covers both directed graphical models and undirected graphical models.


Directed Graphical Models

Directed graphical models use directed connections to represent relationships between variables.

They are useful for representing probabilistic dependencies and reasoning about how variables influence one another within a structured model.

Studying these models helps learners understand concepts such as:

  • Conditional independence

  • Dependency structures

  • Probabilistic reasoning

  • Inference

  • Graph-based representations

These ideas are useful in areas ranging from probabilistic AI to Bayesian reasoning.


Undirected Graphical Models

Undirected graphical models represent relationships without assigning directional relationships between variables.

They are particularly useful when the relationships between variables are symmetric or when the goal is to represent a network of dependencies.

Learning both directed and undirected approaches allows students to understand that probabilistic modeling is not based on a single representation.

Different structures are useful for different types of problems.


Understanding Independence

One of the most important concepts in probabilistic machine learning is independence.

Machine-learning models often need to determine whether knowing one variable provides information about another variable.

Graphical models provide a structured way to reason about these relationships.

Understanding independence is important because it can simplify complex probabilistic problems and make inference computationally more manageable.

The exercises therefore encourage students to reason about relationships between variables rather than simply applying formulas mechanically.


Expressive Power of Graphical Models

Another interesting topic is the expressive power of graphical models.

Different model structures can represent different kinds of relationships.

A simple model may not be able to express complicated dependencies, while a more sophisticated structure may represent them efficiently.

Understanding expressive power helps answer an important machine-learning question:

What kinds of relationships can a particular model represent?

This idea connects directly to modern machine learning, where model architecture and representation capacity strongly influence what a system can learn.


Factor Graphs and Message Passing

The collection also explores factor graphs and message passing.

Factor graphs provide a structured representation of complex probabilistic relationships.

Message passing algorithms then allow information to move through the graph so that different variables can influence one another during inference.

This is an important concept because many probabilistic inference problems would be extremely difficult to solve directly.

Message passing provides a systematic way to break complicated problems into smaller computational components.


Hidden Markov Models

Another important topic is Hidden Markov Model inference.

Hidden Markov Models are used when the system being studied contains hidden states that cannot be directly observed.

Instead, we observe outputs generated by those hidden states and attempt to infer what is happening internally.

This idea has applications in:

  • Speech recognition

  • Sequence analysis

  • Natural language processing

  • Time-series modeling

  • Biological sequence analysis

  • Pattern recognition

Studying HMM inference gives learners an important introduction to reasoning about sequential and hidden information.


Model-Based Learning

The collection also examines model-based learning.

Model-based approaches attempt to construct a mathematical representation of how data is generated or structured.

Instead of treating the model purely as a prediction machine, the learner attempts to understand the underlying data-generating process.

This perspective is particularly valuable in probabilistic machine learning because it emphasizes understanding the structure behind observations.


Independent Component Analysis

One of the topics included under model-based learning is Independent Component Analysis, commonly known as ICA.

ICA attempts to discover underlying independent components within observed data.

A classic intuition is the problem of separating several mixed signals into their underlying sources.

This idea has connections with:

  • Signal processing

  • Representation learning

  • Blind source separation

  • Feature extraction

  • Unsupervised learning

ICA demonstrates how mathematical assumptions about data can be used to discover hidden structure.


Unnormalised Models

The collection also discusses unnormalised models, an important concept in probabilistic modeling.

In some probabilistic models, calculating the normalization factor directly can be computationally difficult.

Rather than avoiding such models completely, researchers can develop learning and inference techniques that work with the unnormalised representation.

This topic is particularly interesting for advanced machine-learning students because it introduces challenges that arise when probability distributions become mathematically or computationally difficult to handle.


Sampling

Sampling is another major area covered by the collection.

In many machine-learning problems, calculating an exact probability or expectation can be difficult.

Sampling provides an alternative approach.

Instead of calculating everything exactly, an algorithm can generate representative samples and use those samples to estimate the quantity of interest.

This idea forms the foundation of many statistical and probabilistic methods.


Monte Carlo Integration

Monte Carlo methods use randomness and repeated sampling to estimate quantities that may be difficult to calculate analytically.

The basic intuition is powerful:

Instead of solving a complicated problem exactly, we can sometimes approximate its solution by generating enough representative random samples.

Monte Carlo methods are widely used in:

  • Bayesian inference

  • Statistical estimation

  • Simulation

  • Numerical integration

  • Probabilistic modeling

  • Scientific computing

The collection includes sampling and Monte Carlo integration as part of its broader focus on probabilistic machine learning.


Variational Inference

Variational inference is another advanced topic included in the work.

It is used when direct probabilistic inference is computationally difficult.

The central idea is to transform a difficult inference problem into an optimization problem.

Instead of trying to calculate a complicated probability distribution directly, we construct a simpler approximation and optimize it so that it becomes as useful as possible.

This idea has become extremely important in modern machine learning.


Unsupervised Learning

A particularly important feature of the collection is its strong emphasis on unsupervised learning.

In supervised learning, models receive examples with known target outputs.

Unsupervised learning is different. The model attempts to discover useful structure from data without being explicitly given the desired answers.

This can involve:

  • Discovering hidden patterns

  • Finding groups

  • Learning representations

  • Identifying latent variables

  • Modeling probability distributions

  • Understanding relationships within data

The author notes that the collection focuses strongly on unsupervised methods, inference, and learning rather than attempting to comprehensively cover every area of machine learning.


Inference in Machine Learning

Inference is one of the central ideas running through the collection.

In probabilistic machine learning, inference generally means determining what can be concluded from available information.

For example, a model may contain hidden variables, incomplete observations, or uncertain relationships.

Inference attempts to answer questions such as:

  • What is likely to have happened?

  • What hidden state is most probable?

  • How are variables related?

  • What information can be inferred from observations?

  • How uncertain is the conclusion?

Learning and inference are closely connected but represent different computational tasks.


Learning Through Detailed Solutions

An important feature of the collection is that the exercises come with detailed solutions.

This makes the resource more than simply a question bank.

Students can:

  1. Attempt an exercise independently.

  2. Work through the problem manually.

  3. Compare their reasoning with the provided solution.

  4. Identify where their understanding differs.

  5. Revisit the underlying theory.

  6. Try the exercise again.

This process encourages active learning rather than passive reading.


Why Solving Problems Is Different From Reading Theory

Reading a machine-learning textbook can provide conceptual understanding, but solving problems requires a different level of engagement.

When reading, it is easy to think:

“I understand this.”

When solving a problem, the learner has to demonstrate that understanding.

This exposes gaps in knowledge.

For example, a student may understand the general idea of eigenvalues but struggle to perform an eigenvalue decomposition. Similarly, someone may understand gradient descent conceptually but struggle to reason about how the gradient changes during optimization.

Pen-and-paper exercises expose these gaps.


Mathematics Before Coding

The resource does not argue that coding is unimportant.

Instead, it offers a complementary approach.

The author explains that while coding and computer simulations are important in machine learning, pen-and-paper exercises can strengthen mathematical skills, and the two approaches are ideally combined.

A strong learning strategy can therefore be:

Understand the theory → Solve manually → Implement in Python → Experiment with data

This approach provides both conceptual and practical understanding.


Combining Pen-and-Paper With Python

After solving an exercise manually, students can implement the same concept in Python.

For example, after studying:

  • Matrix operations

  • Optimization

  • Sampling

  • Graphical models

  • Hidden Markov Models

a learner can implement simplified versions of those ideas in a Jupyter Notebook.

This creates a powerful connection between mathematics and programming.

The learning cycle becomes:

  • Theory — Understand the concept

  • Pen and paper — Work through the reasoning

  • Python — Implement the concept

  • Experimentation — Observe its behavior

  • Analysis — Connect results back to theory


Who Should Use This Resource?

This collection is particularly useful for learners who already have some foundation in mathematics.

It is suitable for:

  • Machine-learning students

  • Data science students

  • AI students

  • Mathematics students

  • Computer science students

  • Researchers

  • Graduate students

  • Teachers

  • Advanced self-learners

The work assumes that readers have already encountered relevant theory and concepts and want to deepen their understanding through exercises.


What Makes It Different From a Typical ML Tutorial?

Most modern machine-learning tutorials focus heavily on implementation.

You may see:

  • Python code

  • Dataset loading

  • Model training

  • Visualization

  • Performance metrics

  • Library APIs

This collection focuses on something different.

It asks the learner to think through the machine-learning problem.

That makes it particularly useful for developing the kind of mathematical intuition that is difficult to obtain by simply running machine-learning libraries.


Key Topics Covered

The work brings together a broad set of mathematical and probabilistic machine-learning topics.

Major areas include:

  • Linear algebra

  • Optimization

  • Directed graphical models

  • Undirected graphical models

  • Graphical-model expressive power

  • Factor graphs

  • Message passing

  • Hidden Markov Models

  • Model-based learning

  • Independent Component Analysis

  • Unnormalised models

  • Sampling

  • Monte Carlo integration

  • Variational inference

These topics are explicitly listed in the paper's abstract and contents.


Benefits for Machine Learning Students

Working through these exercises can develop several important skills.

Mathematical Thinking

Students become more comfortable reasoning about mathematical structures rather than memorizing algorithms.

Problem-Solving

Exercises force learners to break complicated problems into smaller steps.

Algorithmic Understanding

Manually working through algorithms helps reveal what happens internally.

Statistical Intuition

Probabilistic exercises develop a better understanding of uncertainty and inference.

Model Understanding

Students learn to think about what a model can represent and what assumptions it makes.

Research Preparation

A stronger mathematical foundation can be valuable for reading machine-learning research papers.


From Beginner ML to Advanced ML

A learner's journey through machine learning often begins with basic concepts such as:

  • Data

  • Features

  • Labels

  • Regression

  • Classification

  • Model evaluation

As the learner progresses, mathematical concepts become increasingly important.

Advanced topics such as graphical models, probabilistic inference, variational methods, and unsupervised learning require significantly deeper mathematical reasoning.

This resource is therefore particularly useful as a bridge between introductory machine learning and more theoretical machine learning.


Download the PDF for free:
 Pen and Paper Exercises in Machine Learning

Final Thoughts

Pen and Paper Exercises in Machine Learning offers a refreshing approach to learning machine learning in an age dominated by programming frameworks and automated tools.

Its central philosophy is valuable: do not only run the algorithm—understand the algorithm.

By working through problems manually, learners can develop stronger intuition for linear algebra, optimization, probability, graphical models, inference, and unsupervised learning.

The collection does not attempt to replace a machine-learning textbook or course. Instead, it works best alongside them, providing the active problem-solving practice needed to turn theoretical knowledge into deeper understanding.

For anyone who wants to move beyond simply using Python libraries and begin understanding the mathematical and probabilistic foundations of machine learning, this is a highly useful resource.


Python Coding challenge - Day 1227| What is the output of the following Python Code?

 


Code Explanation:

๐Ÿ”น 1. Importing partial
from functools import partial
✅ Explanation
partial is imported from Python's built-in functools module.
It creates a new function by fixing (pre-filling) one or more arguments of an existing function.
The returned function requires only the remaining arguments.

Think of it as creating a shortcut version of a function.

functools Module
        │
        ▼
     partial()
        │
        ▼
Creates a New Function

Nothing executes yet.

๐Ÿ”น 2. Defining the Function
def add(a, b):
    return a + b
✅ Explanation

A function named add is created.

It accepts two parameters:

a
b

and returns their sum.

Current Memory

Function

add(a, b)

↓

return a + b

Nothing runs yet because the function is only defined.

๐Ÿ”น 3. Creating a Partial Function
inc = partial(add, 10)
✅ Explanation

partial(add, 10) creates a new function.

The first argument (a) is permanently fixed to 10.

Internally it behaves almost like this:

def inc(b):
    return add(10, b)

Current Memory

add(a, b)

↓

Fix a = 10

↓

inc(b)

Visual Representation

        add(a,b)
           │
           ▼
     partial(add,10)
           │
           ▼
        inc(b)

๐Ÿ”น 4. Calling the Partial Function
inc(5)
✅ Explanation

Python supplies the missing argument.

Already fixed:

a = 10

New argument:

b = 5

Actual function call becomes

add(10, 5)

Current Memory

a = 10

b = 5

๐Ÿ”น 5. Executing add()
add(10, 5)
✅ Explanation

Inside the function:

return 10 + 5

Result

15

๐Ÿ”น 6. Printing the Result
print(inc(5))
✅ Explanation

Python prints the returned value.

Output

15

๐ŸŽฏ Final Output
15

Python Coding Challenge - Question with Answer (ID 160826)

 

Explanation:

-0 — Negative Zero

The expression -0 means negative zero.

But in Python, when using integers:

-0

is simply:

0

So Python treats both as the same integer value.


 == — Equality Operator

The == operator checks whether two values are equal.

Python evaluates:

-0 == 0

Since -0 is equal to 0:

0 == 0

the result is:

True


 print() — Display the Result

The print() function displays the result of the comparison:

print(True)


 Final Output

True


Saturday, 15 August 2026

Mathematics of Deep Learning: An Introduction (De Gruyter Textbook)(Free PDF)

 


Deep learning is often presented as a combination of Python programming, neural networks, datasets, and powerful computing systems. However, underneath all these practical technologies is a strong mathematical foundation. Every neural network performs mathematical operations when it processes data, learns patterns, calculates errors, and improves its predictions.

Mathematics of Deep Learning: An Introduction, published by De Gruyter, focuses on this important connection between mathematics and deep learning. Instead of treating neural networks simply as programming tools, the book helps readers understand the mathematical ideas that explain how and why deep-learning systems work.

This makes the book especially useful for students, researchers, developers, and anyone who wants to move beyond simply using machine-learning libraries and develop a deeper conceptual understanding of artificial intelligence.


Why Mathematics Is Important in Deep Learning

Mathematics provides the language through which machine-learning models are designed and analyzed. A neural network may look like a collection of interconnected nodes, but each connection represents mathematical operations involving data and adjustable parameters.

During training, a model repeatedly makes predictions, measures its errors, and changes its internal parameters. All of these processes depend on mathematical concepts.

Mathematics helps us understand:

  • How data is represented inside a model
  • How neural-network layers transform information
  • How models measure prediction errors
  • How parameters are updated during training
  • Why some models learn faster than others
  • How neural networks represent complex patterns
  • Why certain models perform better on particular problems

Without understanding these foundations, it is possible to use deep-learning tools effectively, but it becomes more difficult to understand what is happening internally.


Download the PDF for free: https://arxiv.org/abs/2407.18384

Linear Algebra and Neural Networks

Linear algebra is one of the most important mathematical areas used in deep learning.

Neural networks work with large amounts of numerical information. Images, text, audio, sensor readings, and other forms of data are converted into numerical representations. These representations are commonly organized using vectors, matrices, and higher-dimensional structures.

Neural-network layers then transform these numerical representations.

Important concepts include:

  • Vectors
  • Matrices
  • Matrix operations
  • Dimensions
  • Vector spaces
  • Linear transformations
  • Distance and similarity
  • High-dimensional data

Understanding linear algebra makes it much easier to understand how neural-network layers process information.


Calculus and the Learning Process

Calculus plays a major role in understanding how neural networks learn.

A neural network contains many parameters that need to be adjusted during training. The learning process needs to determine how changes in these parameters affect the model's performance.

Calculus provides the mathematical tools needed to study these changes.

This is particularly important for understanding gradients and backpropagation. Backpropagation allows information about prediction errors to move backward through a neural network so that the model can determine how its parameters should be changed.

Calculus helps explain:

  • Gradients
  • Derivatives
  • Backpropagation
  • Parameter updates
  • Optimization
  • Sensitivity to changes
  • Neural-network training

A basic understanding of calculus therefore makes the training process of deep neural networks much less mysterious.


Optimization in Deep Learning

Training a neural network can be viewed as an optimization problem.

A model begins with parameters that are generally not ideal. During training, it attempts to find better parameter values that produce more accurate predictions.

Optimization provides the mathematical framework for this process.

The objective is generally to find a configuration of the model that minimizes its error while maintaining good performance on unseen data.

Important optimization ideas include:

  • Objective functions
  • Loss functions
  • Gradients
  • Learning rates
  • Local and global minima
  • Optimization algorithms
  • Convergence

Optimization is one of the reasons mathematics is so important in modern AI. Training a large neural network involves solving an extremely complicated optimization problem involving potentially millions or billions of parameters.


Probability and Machine Learning

Probability provides another important foundation for deep learning.

Machine-learning models often need to make predictions in situations where the available information is incomplete or uncertain. Probability gives us a way to represent and reason about this uncertainty.

For example, instead of simply saying that an image belongs to a particular category, a classification model can provide probabilities associated with different possible categories.

Probability also helps in understanding:

  • Uncertainty
  • Random variables
  • Data distributions
  • Classification
  • Statistical relationships
  • Prediction confidence
  • Noisy data

This makes probability particularly useful for understanding how machine-learning systems deal with uncertainty.


Statistics and Data

Deep learning depends heavily on data, and statistics provides the tools required to understand that data.

Before training a model, we need to understand the characteristics of the dataset. After training, we also need to determine whether the model has actually learned useful patterns.

Statistics helps with questions such as:

  • Is the dataset representative?
  • Are there unusual observations?
  • Is the model overfitting?
  • How well does the model generalize?
  • How reliable are the predictions?
  • How should model performance be evaluated?

A model can have excellent performance on its training data while performing poorly on new data. Statistical thinking helps identify and understand this problem.


Neural Networks as Mathematical Models

A neural network can be understood as a mathematical model that learns a relationship between inputs and outputs.

The network receives information, transforms it through multiple layers, and produces a result.

Each layer performs a particular transformation. As information moves through the network, its representation changes.

For example, in image recognition, early stages may identify simple visual patterns, while deeper stages can combine those patterns into more meaningful structures.

This hierarchical processing is one of the important characteristics of deep learning.


The Importance of Nonlinear Functions

Nonlinearity is a fundamental concept in deep learning.

Real-world relationships are rarely completely simple or linear. Images, language, financial data, biological information, and human behavior can contain highly complicated relationships.

Nonlinear functions allow neural networks to model these complex relationships.

Without nonlinear components, adding many layers to a neural network would provide much less additional expressive power.

Nonlinearity allows neural networks to:

  • Learn complicated relationships
  • Create complex decision boundaries
  • Represent different types of patterns
  • Model real-world problems
  • Build powerful hierarchical representations

This is one of the key ideas that separates modern deep neural networks from simple linear models.


Classification and Regression

Machine learning is commonly divided into different types of predictive problems.

Classification

Classification involves predicting a category.

Examples include:

  • Spam or not spam
  • Cat or dog
  • Fraudulent or legitimate
  • Disease category
  • Customer segment

The mathematical objective is to learn patterns that distinguish different groups of data.

Regression

Regression focuses on predicting numerical values.

Examples include:

  • House prices
  • Temperature
  • Sales
  • Demand
  • Revenue
  • Stock-related measurements

Understanding classification and regression provides an important foundation for understanding how neural networks are applied to real-world problems.


The Universal Approximation Idea

One of the interesting theoretical ideas associated with neural networks is their ability to approximate complicated functions.

The universal approximation perspective shows why neural networks can be extremely expressive. Under suitable conditions, neural networks can approximate a wide range of functions.

This does not mean that every neural network automatically solves every problem. Instead, it provides theoretical insight into why neural networks can represent complex relationships when they have appropriate architectures and sufficient capacity.

This concept connects the theory of mathematical functions with practical deep-learning systems.


Supervised Learning

In supervised learning, a model learns from examples where the desired outcome is already known.

For instance, a dataset might contain images together with their corresponding labels. The model studies these examples and attempts to learn the relationship between the input and the target.

The quality of supervised learning depends heavily on the quality and quantity of the available training data.

Common applications include:

  • Image classification
  • Text classification
  • Fraud detection
  • Medical prediction
  • Sales forecasting
  • Customer prediction

Unsupervised Learning

Unsupervised learning works with data where predefined labels are not available.

Instead of being told exactly what the correct answer is, the model attempts to discover useful patterns or structures within the data.

This can be useful when large amounts of data are available but manually labeling every example would be expensive or impractical.

Applications include:

  • Customer segmentation
  • Anomaly detection
  • Pattern discovery
  • Data exploration
  • Clustering
  • Representation learning

The mathematical challenge is different from supervised learning because the model has to discover meaningful structure rather than simply reproduce known labels.


Logistic Regression and Neural Networks

An interesting aspect of studying machine learning mathematically is seeing how classical machine-learning methods connect with neural networks.

Logistic regression is a relatively simple model used for classification. A single artificial neuron can be understood in relation to this type of model.

By studying this connection, learners can see that neural networks did not appear completely independently from traditional machine learning. Instead, many neural-network ideas can be understood as extensions and combinations of earlier mathematical and statistical concepts.

This provides a useful bridge between classical machine learning and modern deep learning.


Deep Learning and High-Dimensional Data

Modern AI systems often work with extremely high-dimensional data.

An image may contain thousands or millions of numerical values. A language model may process enormous collections of tokens. Scientific datasets can contain measurements across hundreds or thousands of variables.

Mathematics provides the tools needed to reason about these high-dimensional spaces.

Important ideas include:

  • Dimensionality
  • Distance
  • Similarity
  • Data representation
  • Feature spaces
  • Transformations
  • Geometric structure

Understanding high-dimensional data becomes increasingly important as machine-learning models become larger and more sophisticated.


Understanding Backpropagation

Backpropagation is one of the central ideas behind neural-network training.

Rather than treating it simply as a feature provided by a machine-learning library, mathematical study reveals why it works.

The process allows a neural network to determine how different parts of the model contributed to its prediction error. This information is then used to improve the model during future training iterations.

Understanding backpropagation helps explain:

  • How neural networks learn
  • How errors move through layers
  • How parameters are adjusted
  • Why gradients are important
  • Why deep networks can be trained

It is one of the clearest examples of mathematics directly powering modern AI.


Theoretical Understanding vs Practical Implementation

There are two complementary ways to learn deep learning.

Practical Approach

The practical approach focuses on:

  • Python
  • NumPy
  • PyTorch
  • TensorFlow
  • Datasets
  • Model training
  • Neural-network architectures

Mathematical Approach

The mathematical approach focuses on:

  • Linear algebra
  • Calculus
  • Probability
  • Statistics
  • Optimization
  • Mathematical modeling
  • Theoretical analysis

A strong deep-learning learner benefits from both.

Programming allows you to build and experiment with models, while mathematics helps you understand why those models behave the way they do.


Who Should Read This Book?

This book is particularly useful for readers who already have some mathematical background and want to connect it with deep learning.

It can be valuable for:

  • Mathematics students
  • Computer science students
  • Data science students
  • Machine-learning students
  • AI researchers
  • Software developers
  • Teachers and educators
  • Anyone interested in the theory of deep learning

It is especially relevant for learners who feel that many deep-learning tutorials explain how to use a model but do not sufficiently explain why the model works.


What You Can Learn From the Book

The book provides a mathematical perspective on several important areas of machine learning and deep learning.

Key learning areas include:

  • Foundations of machine learning
  • Artificial neural networks
  • Classification
  • Regression
  • Logistic regression
  • Nonlinear activation functions
  • Optimization
  • Supervised learning
  • Unsupervised learning
  • Neural-network approximation
  • Mathematical foundations of deep learning

These topics help create a bridge between mathematical theory and modern artificial intelligence.


Why This Book Is Relevant Today

Artificial intelligence is developing rapidly, and many people are learning AI through high-level tools and frameworks.

However, frameworks can hide the mathematics underneath the implementation.

When a library trains a neural network, it is still performing mathematical operations involving vectors, matrices, derivatives, probability, optimization, and functions.

As AI systems become increasingly sophisticated, understanding these foundations can become an important advantage.

Mathematical knowledge can help learners move from simply following tutorials to critically analyzing models, understanding their limitations, and developing new approaches.


Hard Copy:Mathematics of Deep Learning: An Introduction (De Gruyter Textbook)

Kindle: Mathematics of Deep Learning: An Introduction (De Gruyter Textbook)

Download the PDF for free: https://arxiv.org/abs/2407.18384

Final Thoughts

Mathematics of Deep Learning: An Introduction provides an excellent perspective for anyone interested in understanding the mathematical foundation of modern artificial intelligence.

Deep learning is not only about neural-network architectures or programming libraries. It is also about mathematics: representing information, transforming data, measuring errors, optimizing parameters, modeling uncertainty, and understanding complex functions.

The most valuable takeaway is that mathematics and deep learning are deeply connected. Once these connections become clear, many concepts that initially seem complicated become much easier to understand.

For students and professionals who want to go beyond simply using AI tools and develop a deeper understanding of how deep-learning systems learn and why they work, this book offers a strong theoretical starting point.

Python Coding Challenge - Question with Answer (ID 150826)

 


Explanation:

1. int("11010", 2)
"11010" is a binary number.
The 2 tells Python to interpret it as base 2.
Binary 11010 = decimal 26.
int("11010", 2)  # 26

2. int("10101", 2)
"10101" is also a binary number.
Python converts it from base 2 to decimal.
Binary 10101 = decimal 21.
int("10101", 2)  # 21

3. ^ — Bitwise XOR

Now Python performs XOR:

  11010
^ 10101
-------
  01111

XOR rules:

Bit 1 Bit 2 Result
0           0             0
0          1             1
1          0             1
1          1             0

So:

11010
10101
-----
01111

01111 in binary = 15 in decimal.

4. print(...)

Finally, print() displays the result:

15

1. int("11010", 2)

  • "11010" is a binary number.
  • The 2 tells Python to interpret it as base 2.
  • Binary 11010 = decimal 26.
int("11010", 2) # 26

2. int("10101", 2)

  • "10101" is also a binary number.
  • Python converts it from base 2 to decimal.
  • Binary 10101 = decimal 21.
int("10101", 2) # 21

3. ^ — Bitwise XOR

Now Python performs XOR:

11010
^ 10101
-------
01111

XOR rules:

Bit 1Bit 2Result
000
011
101
110

So:

11010
10101
-----
01111

01111 in binary = 15 in decimal.

4. print(...)

Finally, print() displays the result:

15

✅ Final Output

15
15

Friday, 14 August 2026

How to Create the Indian Flag in Python | Ashoka Chakra with 24 Spokes

 


How to Draw the Indian National Flag in Python Using NumPy and Matplotlib ๐Ÿ‡ฎ๐Ÿ‡ณ

Python is not only useful for data science and automation—it can also be used to create meaningful graphical illustrations. In this tutorial, we will draw the Indian National Flag (Tiranga) using Python, NumPy, and Matplotlib.

The program creates the three-color flag and draws the Ashoka Chakra with 24 equally spaced spokes at the center.

๐Ÿ‡ฎ๐Ÿ‡ณ Indian National Flag Specifications

Before writing the code, it is important to understand the basic specifications of the Indian National Flag.

According to the Flag Code of India, 2002, the flag:

  • Has three equal horizontal panels.

  • Uses India saffron (Kesari) at the top.

  • Has white in the middle.

  • Uses India green at the bottom.

  • Contains a navy-blue Ashoka Chakra in the center of the white panel.

  • The Ashoka Chakra has 24 equally spaced spokes.

  • Has a rectangular 3:2 length-to-height ratio.

The Flag Code has also been amended to allow hand-spun/hand-woven or machine-made cotton, polyester, wool, silk, or khadi bunting for physical flags. Those material requirements are separate from creating a digital Python illustration.

๐Ÿ Libraries Used

We only need two main Python libraries:

import numpy as np
import matplotlib.pyplot as plt

We also use Rectangle and Circle from Matplotlib to construct the flag and Ashoka Chakra.

from matplotlib.patches import Rectangle, Circle

๐Ÿ“ Creating the Flag

We use a width of 3 and a height of 2 to maintain the required 3:2 ratio.

width = 3
height = 2
band = height / 3

Since the flag contains three equal panels, each band has a height of:

2 / 3

๐ŸŽจ Adding the Three Bands

The three colors are added using Matplotlib's Rectangle patch.

for i, color in enumerate([green, white, saffron]):
    ax.add_patch(
        Rectangle(
            (0, i * band),
            width,
            band,
            facecolor=color,
            edgecolor="none"
        )
    )

The list is written from bottom to top because Matplotlib's coordinate system starts at the bottom:

Green
White
Saffron

Visually, the result is:

Saffron
White
Green

๐Ÿ”ต Creating the Ashoka Chakra

The Chakra is positioned at the exact center of the flag:

cx = width / 2
cy = height / 2

We then create the outer Chakra circle:

chakra_radius = band * 0.45

ax.add_patch(
    Circle(
        (cx, cy),
        chakra_radius,
        fill=False,
        color=navy,
        linewidth=3
    )
)

๐Ÿ”น Adding 24 Spokes

The Ashoka Chakra contains 24 equally spaced spokes.

NumPy makes calculating the angles easy:

for i in range(24):
    angle = 2 * np.pi * i / 24

For every angle, we calculate the starting and ending points of the spoke:

x1 = cx + inner_radius * np.cos(angle)
y1 = cy + inner_radius * np.sin(angle)

x2 = cx + chakra_radius * np.cos(angle)
y2 = cy + chakra_radius * np.sin(angle)

Then Matplotlib draws the spoke:

ax.plot(
    [x1, x2],
    [y1, y2],
    color=navy,
    linewidth=1.5
)

๐Ÿ’ป Complete Python Code

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Circle

width = 3
height = 2
band = height / 3

saffron = "#FF671F"
white = "#FFFFFF"
green = "#046A38"
navy = "#06038D"

fig, ax = plt.subplots(figsize=(12, 8))

for i, color in enumerate([green, white, saffron]):
    ax.add_patch(
        Rectangle(
            (0, i * band),
            width,
            band,
            facecolor=color,
            edgecolor="none"
        )
    )

cx = width / 2
cy = height / 2

chakra_radius = band * 0.45

ax.add_patch(
    Circle(
        (cx, cy),
        chakra_radius,
        fill=False,
        color=navy,
        linewidth=3
    )
)

inner_radius = chakra_radius * 0.12

ax.add_patch(
    Circle(
        (cx, cy),
        inner_radius,
        fill=False,
        color=navy,
        linewidth=2
    )
)

for i in range(24):
    angle = 2 * np.pi * i / 24

    x1 = cx + inner_radius * np.cos(angle)
    y1 = cy + inner_radius * np.sin(angle)

    x2 = cx + chakra_radius * np.cos(angle)
    y2 = cy + chakra_radius * np.sin(angle)

    ax.plot(
        [x1, x2],
        [y1, y2],
        color=navy,
        linewidth=1.5
    )

ax.set_xlim(0, width)
ax.set_ylim(0, height)
ax.set_aspect("equal")
ax.axis("off")

plt.tight_layout()
plt.show()

๐Ÿ“š What You Learn From This Project

This small Python project demonstrates several useful concepts:

  • NumPy trigonometric functions

  • for loops

  • Matplotlib figures and axes

  • Rectangles and circles

  • Coordinate systems

  • Sine and cosine

  • Angles and radians

  • Mathematical visualization

  • Drawing geometric patterns with Python

The project is a great example of how mathematics + Python + visualization can be combined to create something meaningful.

๐Ÿ‡ฎ๐Ÿ‡ณ Final Result

The program generates a digital representation of the Indian National Flag with:

Saffron + White + Green + Navy Blue Ashoka Chakra + 24 Spokes

The official Ministry of Home Affairs continues to publish the Flag Code and related guidance, including the 2021 and 2022 amendments.

Note: This Python program is an educational digital illustration. Compliance requirements for an actual physical National Flag—including material, manufacture, display, and handling—are governed separately by the Flag Code of India and the Prevention of Insults to National Honour Act.

๐Ÿš€ Conclusion

Drawing the Indian National Flag with Python is a simple but powerful visualization project. It shows that Python can go beyond traditional programming tasks and can be used to create geometric artwork and educational visualizations.

If you are learning NumPy and Matplotlib, this is a great beginner-friendly project to understand how mathematical coordinates, loops, and graphical objects work together.

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (346) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (359) Bootcamp (15) C (78) C# (12) C++ (83) cloud (1) Course (93) Coursera (305) Cybersecurity (36) data (10) Data Analysis (47) Data Analytics (31) data management (16) Data Science (435) Data Strucures (19) Deep Learning (222) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (9) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (78) Git (13) Google (55) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (407) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (35) Python (1377) Python Coding Challenge (1261) Python Library (14) Python Mathematics (19) Python Mistakes (51) Python Pattern Challenge (15) Python Quiz (646) Python Tips (112) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (22) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)