Wednesday, 23 September 2026

Python Turtle: A Heart Made of Code







 Code:

import turtle import math import time screen = turtle.Screen() screen.setup(700, 700) screen.bgcolor("#03000a") screen.tracer(0) t = turtle.Turtle() t.hideturtle() t.speed(0) colors = ["#ff1744", "#ff4081", "#d500f9", "#7c4dff", "#00e5ff"] # ❤️ Neon Heart for i in range(360): a = math.radians(i) x = 16 * math.sin(a) ** 3 y = ( 13 * math.cos(a) - 5 * math.cos(2*a) - 2 * math.cos(3*a) - math.cos(4*a) ) scale = 15 t.penup() t.goto(0, 0) t.pendown() t.color(colors[i % len(colors)]) t.goto(x * scale, y * scale) t.dot(3 + i % 3) screen.update() time.sleep(0.02) # ✨ Glowing Center for r in range(25, 2, -3): t.penup() t.goto(0, -r) t.dot(r, colors[r % len(colors)]) screen.update() time.sleep(0.06) # ⭐ Small Sparkles for i in range(25): angle = i * 137.5 radius = 230 + (i % 4) * 15 x = radius * math.cos(math.radians(angle)) y = radius * math.sin(math.radians(angle)) t.penup() t.goto(x, y) t.dot(2 + i % 3, colors[i % len(colors)]) screen.update() time.sleep(0.03) turtle.done()


























Explanation:

1. Import Libraries
import turtle
import math
import time
turtle → Drawing.
math → Mathematical calculations.
time → Animation delays.

2. Create the Screen
screen = turtle.Screen()
screen.setup(700, 700)
screen.bgcolor("#03000a")
screen.tracer(0)
Creates a 700 × 700 window.
Sets a dark background.
tracer(0) gives manual screen updates.

3. Configure the Turtle
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
Creates the turtle.
Hides the cursor.
Sets maximum drawing speed.

4. Define Neon Colors
colors = [...]
Stores the colors used for the heart, glow, and sparkles.

5. Generate the Heart
for i in range(360):
Creates 360 points around the heart.
a = math.radians(i)
Converts the angle from degrees to radians.

6. Calculate Heart Coordinates
x = 16 * math.sin(a) ** 3
Calculates the X-coordinate using the heart equation.
y = (
    13 * math.cos(a)
    - 5 * math.cos(2*a)
    - 2 * math.cos(3*a)
    - math.cos(4*a)
)
Calculates the Y-coordinate.
Together, these equations create the heart shape.

7. Scale the Heart
scale = 15
Enlarges the mathematical heart.

8. Move to Each Point
t.penup()
t.goto(0, 0)
t.pendown()
Moves to the center without drawing.
Starts drawing from the center.

9. Draw the Neon Heart
t.color(colors[i % len(colors)])
t.goto(x * scale, y * scale)
t.dot(3 + i % 3)
Cycles through neon colors.
Draws each heart point.
Adds small glowing dots.

10. Animate the Heart
screen.update()
time.sleep(0.02)
Updates the screen.
Adds a small delay for the drawing animation.

11. Create the Center Glow
for r in range(25, 2, -3):
Creates several shrinking circles.
t.goto(0, -r)
t.dot(r, colors[r % len(colors)])
Places colorful dots near the center.
Creates a glowing effect.

12. Add Sparkles
for i in range(25):
Creates 25 sparkles.
angle = i * 137.5
radius = 230 + (i % 4) * 15
Generates different angles and distances.
Spreads the sparkles around the heart.

13. Calculate Sparkle Positions
x = radius * math.cos(math.radians(angle))
y = radius * math.sin(math.radians(angle))
Converts the angle and radius into X/Y coordinates.

14. Draw the Sparkles
t.goto(x, y)
t.dot(2 + i % 3, colors[i % len(colors)])
Moves to each position.
Draws colorful dots of different sizes.

15. Finish
turtle.done()
Keeps the Turtle window open and finishes the animation.










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

 




Code Explanation:

1️⃣ Creating an Empty Dictionary
d = {}

An empty dictionary is created.

d → {}

Currently, there is no key named "x".

2️⃣ Using setdefault() for the First Time
a = d.setdefault("x", [])

setdefault() checks whether "x" already exists in d.

Since "x" does not exist, Python:

Creates the empty list []
Stores it as the value of "x"
Returns that same list to a

So:

d → {"x": []}
a → []

Importantly:

a and d["x"] refer to the SAME list.

3️⃣ Adding 10
a.append(10)

Because a and d["x"] point to the same list:

a → [10]
d → {"x": [10]}

No new list is created.

4️⃣ Using setdefault() Again
b = d.setdefault("x", [])

Now "x" already exists.

Therefore, Python does not replace the existing value with a new list.

Instead, it returns the existing list:

b → [10]
d["x"] → [10]

So now:

a is b

is True.

Both variables refer to the same list.

5️⃣ Adding 20
b.append(20)

Since b refers to the same list:

b → [10, 20]

Therefore d["x"] also becomes:

d → {"x": [10, 20]}

6️⃣ Printing the Value
print(d["x"])

The value stored under "x" is:

[10, 20]

✅ Final Output
[10, 20]

200 Days Python Coding Challenges with Explanation

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







Code Explanation:

1. Import ExitStack
from contextlib import ExitStack

ExitStack is a context manager from Python's contextlib module.

It allows us to register cleanup callbacks dynamically and execute them when the stack is closed.

2. Create an Empty List
x = []

An empty list is created.

x = []

This list will store "A" and "B" when their callbacks execute.

3. Create the First ExitStack
with ExitStack() as s:

A new ExitStack is created and assigned to s.

The with block automatically calls s.close() when the block finishes.

Initially:

s = ExitStack
x = []

4. Register Callback "A"
s.callback(x.append, "A")

This does not immediately append "A".

Instead, it registers the operation:

x.append("A")

to be executed when s is closed.

Conceptually:

s
└── callback: append("A")

Still:

x = []

5. pop_all() — The Most Important Line
t = s.pop_all()

This is the key trick.

pop_all() transfers all callbacks from s to a new ExitStack.

Before:

s
└── callback("A")

After:

s → empty

t
└── callback("A")

So the callback for "A" is no longer owned by s.

Important:

pop_all() does not execute the callback.

Therefore:

x = []

6. Register Callback "B"
s.callback(x.append, "B")

Now "B" is registered with the original stack s.

Remember:

s → callback("B")

t → callback("A")

They are now completely separate stacks.

7. Print x Inside the with Block
print(x)

Neither callback has executed yet.

Therefore:

x = []

Output:

[]

8. Exit the with Block

When the with block ends, Python automatically closes s.

At this point:

s → callback("B")
t → callback("A")

Only s is automatically closed.

Therefore, callback "B" executes.

Conceptually:

x.append("B")

So:

x = ['B']

⚠️ But there is an important correction: The exact code as written therefore produces:

[]
['B', 'A']

not [] / ['A'].

9. Execute Callback "B"

Because "B" belongs to s, it runs when the with block exits:

x.append("B")

Now:

x = ['B']

10. t.close()
t.close()

Now the second stack t is explicitly closed.

Remember, t received the "A" callback through pop_all().

Therefore:

x.append("A")

executes.

Now:

x = ['B', 'A']

11. Final print(x)
print(x)

The final list is:

[] 
['B', 'A']

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

 


Code Explanation:

1️⃣ Importing Counter
from collections import Counter

Counter is a class from Python's built-in collections module.

It is used to count how many times each value occurs.

For example:

Counter([1, 1, 2])

produces:

Counter({1: 2, 2: 1})

2️⃣ Creating the Data
data = [2, 3, 2, 4, 3, 2]

The list contains:

2 → 3 times
3 → 2 times
4 → 1 time

So the frequency is:

2 : 3
3 : 2
4 : 1

3️⃣ Creating the Counter
c = Counter(data)

Counter automatically counts every element in data.

Conceptually:

c
{
    2: 3,
    3: 2,
    4: 1
}

So:

c[2]  # 3
c[3]  # 2
c[4]  # 1

4️⃣ Finding the Most Common Element
x = c.most_common(1)

most_common() returns elements sorted by their frequency.

The argument 1 means:

Return only the one most frequent element.

The counts are:

2 → 3
3 → 2
4 → 1

Therefore, 2 is the most frequent.

The result is returned as a list of tuples:

[(2, 3)]

Here:

2 → the element
3 → its frequency

5️⃣ Printing the Result
print(x)

Since:

x = [(2, 3)]

Python prints:

✅ Final Output
[(2, 3)]


100 Python Programs for Beginner with explanation

Physics-based Deep Learning (Free PDF)

 


Physics-based Deep Learning: Combining Deep Learning with Physical Simulations

Physics-based Deep Learning (PBDL) is a practical learning resource that explores how deep learning can be combined with physical models and numerical simulations. The work is authored by Nils Thuerey, Benjamin Holzschuh, Philipp Holl, Georg Kohl, Mario Lino, Qiang Liu, Patrick Schnell, and Felix Trost. The current arXiv version is v4, revised in March 2025.

Unlike a traditional deep learning resource that focuses primarily on image, text, or tabular datasets, this book focuses on physical simulations and scientific computing. It explores how neural networks can work together with existing knowledge about physical systems instead of treating the problem as purely data-driven.

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

What Is Physics-based Deep Learning?

Physics-based Deep Learning brings together two major areas:

  • Deep Learning — neural networks learn patterns from data.

  • Physics-based Modeling — physical laws and numerical simulations describe how real systems behave.

The central idea is not simply to replace traditional simulation methods with neural networks. Instead, the goal is to find useful ways to combine learned models with physical knowledge and numerical techniques.

This creates a hybrid approach where machine learning can help accelerate simulations, estimate physical states, solve difficult inverse problems, or incorporate physical constraints into the learning process.

Why Combine Physics and Deep Learning?

Traditional physical simulations can be computationally expensive, particularly when a problem must be solved repeatedly.

For example, simulations involving:

  • Fluid flows

  • Heat transfer

  • Physical dynamics

  • Engineering systems

  • Environmental processes

  • Complex scientific phenomena

may require substantial computational resources.

A neural network can potentially learn a specialized approximation for a particular problem domain. Once trained, that learned model can support repeated simulations much more efficiently in suitable scenarios. The PBDL authors describe this as an opportunity to combine specialized neural networks with established numerical solvers rather than discarding traditional simulation methods.

A Hands-on Learning Approach

One of the most interesting aspects of the resource is its practical focus.

The authors describe it as a hands-on and comprehensive guide, with concepts accompanied by interactive Jupyter notebooks. This makes the material particularly useful for learners who want to experiment with the methods rather than only read about them.

The notebooks allow readers to explore concepts computationally and understand how deep learning interacts with physical simulations.

Data-Driven Physics

One approach is to use data generated by real or simulated physical systems.

In this setting, the physical simulator can produce training data, while the neural network learns relationships from that data.

The important distinction is that the physical model provides the source of information, but the learning process itself may not directly enforce the physical rules.

This approach can be useful when large amounts of simulation data are available and a learned approximation is valuable.

Physical Loss Constraints

A more tightly connected approach incorporates physical knowledge into the learning objective.

Instead of asking a neural network to simply reproduce training examples, the learning process can also account for whether its predictions are consistent with relevant physical behavior.

This idea is closely related to physics-informed learning, where physical constraints help guide the training process.

The benefit is that the model does not have to rely entirely on patterns found in data. Physical knowledge can become part of the learning process.

Differentiable Physics

Another major topic is differentiable simulation.

A differentiable simulator allows information about how a simulation changes to flow through the learning process. This creates a much closer interaction between neural networks and numerical simulation.

Instead of treating the simulator as a completely separate black box, the learning algorithm can interact with it during optimization.

The PBDL material describes these approaches as an especially tight integration between deep learning and physical simulations.

Forward and Inverse Problems

Physics-based Deep Learning also considers two important types of scientific problems.

Forward Problems

A forward problem starts with known physical parameters or conditions and attempts to predict what happens next.

For example, a model might predict how a physical system evolves over time.

Inverse Problems

An inverse problem works in the opposite direction.

Instead of starting with known parameters and predicting observations, the goal is to use observations to determine unknown properties of the physical system.

Deep learning can be particularly useful for these problems because neural networks can learn complex relationships between observations and underlying physical parameters.

Reinforcement Learning for Physical Systems

The resource also explores reinforcement learning in the context of physical simulations.

In reinforcement learning, an agent learns by interacting with an environment and receiving feedback.

When combined with physics-based environments, this can be used to investigate problems involving:

  • Control

  • Optimization

  • Physical decision-making

  • Dynamic systems

  • Simulation-based learning

This creates a connection between scientific simulation and intelligent control systems.

Generative AI and Physical Simulation

The newer PBDL v0.3 release adds a major section on generative AI, including diffusion-based approaches and physics-based constraints. The authors describe this as a substantial new chapter in the updated version.

This is particularly interesting because generative models can produce possible physical states or system behaviors, while physics-based constraints can help guide those predictions toward physically meaningful results.

It represents an emerging direction where generative AI is not used only for images or text but also for scientific and physical modeling.

Scientific Foundation Models

The authors connect these developments to the broader idea of scientific foundation models.

Traditional foundation models have largely focused on domains such as language, vision, and multimodal data. Physics-based learning introduces the possibility of models that can work with scientific systems while incorporating physical knowledge.

This could become important for areas where predictions need to respect the behavior of the underlying physical system.

Practical Applications

Physics-based Deep Learning can be relevant to a wide range of scientific and engineering problems.

Potential applications include:

  • Fluid simulation

  • Weather and environmental modeling

  • Engineering design

  • Computational physics

  • Physical system control

  • Surrogate modeling

  • Inverse problems

  • Scientific machine learning

  • Simulation acceleration

The official project materials specifically position PBDL around combinations of physical modeling, numerical simulation, and neural-network-based learning.

What Makes This Resource Different?

The biggest difference is its focus on combining, rather than replacing.

The goal is not simply:

Physics → replaced by AI

Instead, the broader philosophy is:

Physics + Numerical Methods + Deep Learning

This is important because established numerical methods already contain decades of knowledge about physical systems. Combining them with machine learning can create specialized computational approaches while preserving valuable physical information.

Who Should Read It?

This resource is particularly suitable for:

  • Deep learning students

  • Physics students

  • Computational scientists

  • Scientific machine learning researchers

  • Engineers

  • Researchers working with simulations

  • ML practitioners interested in scientific applications

  • Students interested in differentiable physics

It is more specialized than a general deep learning book, so readers will benefit from having some background in machine learning and numerical or physical simulation concepts.

Strengths

1. Strong Practical Focus

The resource provides interactive Jupyter notebooks alongside many concepts.

2. Combines Multiple Fields

It connects deep learning, numerical simulation, physics, optimization, and scientific computing.

3. Covers Modern Topics

The current version includes topics such as differentiable physics, reinforcement learning, uncertainty modeling, and generative AI.

4. Useful for Scientific ML

It provides a strong conceptual foundation for understanding how machine learning can be applied to physical simulation problems.

Limitations

This is not a beginner-level introduction to deep learning.

The authors explicitly position the resource as a guide to deep learning in the context of physical simulations rather than an in-depth introduction to basic deep learning or numerical simulation.

Therefore, beginners may need additional resources to learn fundamental neural networks, optimization, and simulation concepts before working through the more advanced material.

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

Final Verdict

Physics-based Deep Learning is an excellent resource for understanding the intersection of deep learning, physics, and computational simulation.

Its most valuable idea is that AI does not necessarily have to operate independently from scientific knowledge. Neural networks can work alongside numerical methods, physical constraints, and differentiable simulations to create new approaches to scientific computing.

The addition of generative AI in the latest version also makes the resource especially relevant to the rapidly developing field of scientific AI.


Linear Algebra Done Right (Free PDF)

 


Linear Algebra Done Right by Sheldon Axler is a well-known textbook that presents linear algebra from a more conceptual and proof-oriented perspective. It is particularly aimed at students taking a second course in linear algebra, including advanced undergraduate mathematics students and beginning graduate students.

The book takes a distinctive approach: instead of introducing determinants as an early tool for solving problems, it focuses first on understanding vector spaces, linear maps, eigenvalues, and the structure of linear operators. Determinants are moved toward the end of the development.

Download the PDF for free: Linear Algebra Done Right

What Makes Linear Algebra Done Right Different?

Many introductory linear algebra courses begin heavily with matrices and computational procedures. Axler takes a different route.

The book emphasizes the underlying mathematical structures behind linear algebra. Instead of asking only how to calculate, it repeatedly asks:

Why does this concept work?

This makes the book particularly valuable for readers who want to understand linear algebra as a mathematical theory rather than simply learn a collection of matrix operations.

Vector Spaces

The book begins with vector spaces, which form the foundation of the subject.

Readers study ideas such as:

  • Vector spaces

  • Subspaces

  • Linear combinations

  • Span

  • Linear independence

  • Bases

  • Dimension

These concepts are essential because they provide a common framework for working with many different mathematical objects.

A vector does not have to be thought of only as a column of numbers. The broader vector-space viewpoint allows functions, polynomials, matrices, and other objects to be treated using the same underlying ideas.

Finite-Dimensional Vector Spaces

The next stage focuses on finite-dimensional spaces.

The book develops the relationship between:

  • Span

  • Independence

  • Bases

  • Dimension

Understanding these concepts helps explain how complicated vector spaces can be represented using a finite collection of fundamental directions or elements.

This is also an important foundation for later topics such as linear transformations, eigenvectors, and matrix representations.

Linear Maps

One of the central themes of the book is the study of linear maps.

A linear map describes a transformation that preserves the essential structure of a vector space.

The book examines:

  • Linear maps

  • Null spaces

  • Ranges

  • Injectivity

  • Surjectivity

  • Invertibility

  • Matrix representations

  • Operators

The focus on linear maps is one of the defining features of Axler's approach. Rather than treating matrices as the primary objects, matrices are often presented as representations of linear maps.

Matrices

Matrices are still an important part of the book, but they are placed into a broader conceptual framework.

Readers learn how matrices can represent linear transformations and how operations on matrices relate to the underlying maps.

This viewpoint can make matrix operations more meaningful because the reader understands what the matrix represents, rather than treating it only as a grid of numbers.

Polynomials

The book also contains a dedicated chapter on polynomials.

Topics include:

  • Polynomial spaces

  • Polynomial coefficients

  • Polynomial division

  • Zeros of polynomials

  • Factorization

  • Complex and real polynomial behavior

Polynomials are especially useful in linear algebra because they provide an important connection to eigenvalues and operators.

Eigenvalues and Eigenvectors

Eigenvalues and eigenvectors are among the most important concepts in modern linear algebra.

The book studies:

  • Eigenvalues

  • Eigenvectors

  • Invariant subspaces

  • Generalized eigenvectors

  • Structure of linear operators

Rather than treating eigenvalues simply as a computational procedure, Axler uses them to understand the deeper structure of linear operators.

This is particularly relevant to areas such as machine learning, dimensionality reduction, optimization, computer graphics, and scientific computing.

Inner Product Spaces

The book then introduces inner product spaces.

These provide the mathematical foundation for concepts involving geometry, angles, orthogonality, and length.

The topic connects algebraic ideas with geometric intuition and prepares the reader for the study of operators on inner product spaces.

Operators on Inner Product Spaces

The book explores how linear operators behave when additional geometric structure is available.

This includes concepts related to:

  • Orthogonality

  • Adjoint operators

  • Self-adjoint operators

  • Normal operators

  • Isometries

  • Spectral theory

These ideas are important in advanced mathematics and also appear in areas of computational science and data analysis.

Complex and Real Vector Spaces

Another important part of the book is the separate treatment of operators on complex and real vector spaces.

This distinction matters because operators can behave differently depending on the underlying field.

The book develops the theory carefully so that readers can understand why certain results work naturally over complex spaces and how corresponding ideas behave over real spaces.

Trace and Determinant

One of the distinctive features of Linear Algebra Done Right is that determinants appear near the end rather than being used as the foundation for the entire subject.

The third edition contains a chapter on Trace and Determinant near the end of the book.

This reflects Axler's philosophy that many fundamental ideas in linear algebra can be understood without making determinants the starting point.

Linear Algebra and Machine Learning

Linear algebra is one of the mathematical foundations of modern machine learning.

Concepts from this book connect naturally to areas such as:

Data Representation

Datasets are frequently represented using vectors and matrices.

Dimensionality Reduction

Methods such as PCA rely heavily on ideas related to vector spaces, eigenvectors, and inner products.

Neural Networks

Neural networks perform large numbers of transformations involving vectors, matrices, and higher-dimensional representations.

Computer Vision

Images can be represented as numerical arrays, while many image-processing operations involve linear transformations.

Optimization

Linear algebra provides important tools for understanding optimization problems used in machine learning.

Therefore, a strong conceptual understanding of linear algebra can help ML practitioners understand what happens underneath high-level libraries.

The Fourth Edition

The book has continued to evolve. The fourth edition was published by Springer in 2024 and is available as an open-access textbook.

The fourth edition contains nine chapters and includes expanded treatment of topics such as the singular value decomposition, along with additional exercises and new material.

The fourth-edition structure includes:

  1. Vector Spaces

  2. Finite-Dimensional Vector Spaces

  3. Linear Maps

  4. Polynomials

  5. Eigenvalues and Eigenvectors

  6. Inner Product Spaces

  7. Operators on Inner Product Spaces

  8. Operators on Complex Vector Spaces

  9. Multilinear Algebra and Determinants

Exercises and Problem Solving

A major component of the book is its exercises.

The fourth edition adds a substantial number of exercises, continuing the book's emphasis on learning through problem solving.

These exercises are important because linear algebra is difficult to master through reading alone. Working through proofs and problems forces the learner to understand how the concepts connect.

Who Should Read This Book?

Linear Algebra Done Right is particularly suitable for:

  • Mathematics students

  • Computer science students with mathematical interests

  • Machine learning students

  • Data science students wanting stronger mathematical foundations

  • Students taking a second linear algebra course

  • Beginning graduate students

  • Readers interested in proofs and abstract mathematical reasoning

It may feel more theoretical than a typical computational linear algebra textbook, so readers looking only for quick matrix calculations may find the approach different from what they expect.

Strengths

1. Conceptual Approach

The book focuses strongly on understanding the structure behind linear algebra.

2. Rigorous Treatment

Definitions, theorems, and proofs are developed carefully.

3. Strong Foundation for Advanced Topics

The treatment of vector spaces, linear maps, eigenvalues, and inner products provides a foundation for more advanced mathematics.

4. Distinctive Determinant-Free Development

Moving determinants toward the end allows many central ideas to be developed independently of them.

5. Open-Access Fourth Edition

The fourth edition is available as an open-access textbook through Springer.

Limitations

The book is not primarily a beginner-friendly computational guide.

It emphasizes abstraction, proofs, and mathematical reasoning. A learner who has never encountered linear algebra may need a gentler introductory resource before tackling it.

It also focuses more on mathematical structure than on direct applications to machine learning, data science, or engineering.

Hard Copy: Linear Algebra Done Right

Download the PDF for free: Linear Algebra Done Right

Final Verdict

Linear Algebra Done Right offers a distinctive way to learn linear algebra by focusing on the ideas that make the subject work.

Its emphasis on vector spaces, linear maps, eigenvalues, inner product spaces, and operators makes it particularly valuable for students who want to move beyond mechanical calculations and develop a deeper mathematical understanding.

For AI, machine learning, and data science learners, the book can provide a strong theoretical foundation behind many of the linear algebra concepts used in modern computational methods.


Python Coding Challenge - Question with Answer (ID 230926)

 




Explanaation:



๐ŸŸข Line 1: 5
5

5 is an integer (int).

So Python knows this is a numeric value.

๐ŸŸก Line 2: None
None

None is a special Python value representing no value / absence of a value.

Its type is:

type(None)

Output:

<class 'NoneType'>

๐Ÿ”ต Line 3: 5 + None

Python now tries to perform:

5 + None

The + operator can add compatible numeric values such as:

5 + 3

But None is not a number.

Python cannot perform:

int + NoneType

So the operation fails.


๐Ÿ”ด What Error Occurs?

Python raises:

TypeError

Because the two operands have incompatible types.

The actual error message is similar to:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Final Ouptut:
Type Error

Books: Python Functions in Depth — Writing Clean, Reusable, and Powerful Code

Tuesday, 22 September 2026

๐Ÿ Python Pattern Challenge — Day 11

 





๐Ÿ Python Pattern Challenge — Day 11

Pattern printing is a great way to strengthen your Python logic, loops, string handling, and problem-solving skills. For Day 11, let's try a different diamond-style pattern where the number of stars increases toward the center and then decreases again.

The twist is that the middle row contains 11 stars, making the pattern slightly different from a regular diamond.

Today's Challenge

Write a Python program to print:

 

Best and cleanest code will be rewarded! ๐Ÿ†


Solution 1 — Using a for Loop

rows = [1, 3, 5, 7, 11, 7, 5, 3, 1] for stars in rows: spaces = (11 - stars) // 2 print(" " * spaces + "* " * stars)




How it works:

The pattern is controlled by this list:

[1, 3, 5, 7, 11, 7, 5, 3, 1]

The number of stars follows:

1 → 3 → 5 → 7 → 11 
11 → 7 → 5 → 3 → 1

And:

spaces = (11 - stars) // 2

calculates the indentation needed to keep every row centered.


Solution 2 — Using Nested Loops

rows = [1, 3, 5, 7, 11, 7, 5, 3, 1] for stars in rows: spaces = (11 - stars) // 2 for _ in range(spaces): print(" ", end="") for _ in range(stars): print("*", end=" ") print()







How it works:

The nested loops separately control:

  • First loop → creates the leading spaces.
  • Second loop → prints the required number of *.
  • Outer loop → moves through each row of the pattern.

This is useful for understanding how loops can control both spacing and repetition.


Solution 3 — Using a while Loop

rows = [1, 3, 5, 7, 11, 7, 5, 3, 1] i = 0 while i < len(rows): stars = rows[i] spaces = (11 - stars) // 2 print(" " * spaces + "* " * stars) i += 1






Here, the same pattern is created using a while loop.

The list stores the number of stars required for every row.


⚡ Short & Clean Code

for s in [1, 3, 5, 7, 11, 7, 5, 3, 1]: 
    print(" " * ((11 - s) // 2) + "* " * s)

๐Ÿ”ฅ Just one loop is enough to generate the complete pattern.


๐Ÿš€ Challenge Yourself

Can you modify this pattern:

  • Generate the star counts without manually writing the list?
  • Take the maximum number of stars using input()?
  • Replace * with numbers?
  • Create the same pattern using a while loop?
  • Create a hollow version of this pattern?
  • Solve it using the shortest possible Python code?

Drop your solution below! ๐Ÿ‘‡

11 Days. 11 Patterns. Stronger Python Logic. ๐Ÿ๐Ÿ”ฅ

Learn • Practice • Grow with CLCODING


100 Python Programs for Beginner with explanation

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (345) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (359) Bootcamp (14) 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 (433) Data Strucures (18) Deep Learning (221) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (9) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (77) 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 (404) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (35) Python (1377) Python Coding Challenge (1250) Python Library (7) Python Mathematics (18) Python Mistakes (51) Python Pattern Challenge (10) Python Quiz (639) 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)