Tuesday, 13 January 2026

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


 Code Explanation:

1. Defining a Custom Metaclass
class Switch(type):

Switch is a metaclass because it inherits from type.

A metaclass controls how classes are created.

2. Overriding the Metaclass __new__ Method
    def __new__(cls, name, bases, dct):
        if name == "Worker":
            bases = (str,)
        return super().__new__(cls, name, bases, dct)

__new__ is called whenever a class using this metaclass is created.

Parameters:

cls → the metaclass (Switch)

name → class name being created

bases → original base classes

dct → class attributes

What it does:

If the class name is "Worker", it replaces its base class with str.

Otherwise, it leaves bases unchanged.

3. Defining the Base Class
class BaseModel: 
    pass

A normal base class with no behavior.

4. Defining Class Worker
class Worker(BaseModel, metaclass=Switch): 
    pass

Step-by-step:

Python prepares to create Worker.

It calls:

Switch.__new__(Switch, "Worker", (BaseModel,), {...})

Inside __new__:

name == "Worker" → True

bases is replaced with (str,)

So Worker is actually created as:

class Worker(str): pass


Not as Worker(BaseModel).

5. Printing the Base Classes
print(Worker.__bases__)

Shows the actual base classes of Worker.

Since the metaclass changed it, the base is str.

6. Final Output
(<class 'str'>,)


Final Answer
✔ Output:
(<class 'str'>,)

100 Python Programs for Beginner with explanation

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


 

Code Explanation:

1. Defining a Custom Metaclass
class Meta(type):

Meta is a metaclass because it inherits from type.

A metaclass controls how classes are created.

2. Overriding the __new__ Method of the Metaclass
    def __new__(cls, name, bases, dct):
        dct["hello"] = lambda self: "hi"
        return super().__new__(cls, name, bases, dct)

__new__ runs when a class is being created.

Parameters:

cls → the metaclass (Meta)

name → name of the class being created ("A")

bases → base classes

dct → class attribute dictionary

What it does:

Adds a new method named hello into the class dictionary.

hello is a function that returns "hi".

So every class created with this metaclass will automatically get a hello() method.

3. Creating Class A Using the Metaclass
class A(metaclass=Meta): pass

Class A is created using metaclass Meta.

During creation:

Meta.__new__ is called.

hello is injected into the class.

Class A is created with method hello.

So now:

A.hello exists

4. Creating an Instance and Calling hello
print(A().hello())

A() creates an instance of A.

.hello() calls the injected method.

The lambda returns "hi".

5. Final Output
hi

Final Answer
✔ Output:
hi

Data Science and Machine Learning for Beginners: A Practical Introduction to Data Analysis, Algorithms, and Real-World Applications


 


In a world driven increasingly by data and intelligent systems, the fields of data science and machine learning have become core competencies for professionals across industries. Yet for newcomers, the landscape can seem overwhelming — filled with complex algorithms, dense statistics, and jargon that feels nearly impenetrable.

Data Science and Machine Learning for Beginners: A Practical Introduction to Data Analysis, Algorithms, and Real-World Applications is a book designed specifically to ease that transition. It offers a clear, structured, and hands-on introduction to foundational concepts, tools, and techniques — all oriented toward real problems and real results.


Why This Book Matters

Many resources for data science and machine learning assume extensive prior experience with mathematics, programming, or statistics. This book takes a different approach: it assumes little to no background knowledge, and builds understanding step by step. It is ideal for students, career changers, aspiring analysts, and self-taught learners who want a practical, accessible entry point into the field.

The emphasis throughout is on clarity and application — not abstract theory divorced from real use cases. Readers learn to think like data scientists, not just memorize formulas or algorithms.


What You’ll Learn

The book is organized to guide you through a complete learning journey, from basic concepts to hands-on techniques:

1. Foundations of Data Science

The early chapters set the stage with explanations of what data science and machine learning actually are, why they matter, and how they fit together. You learn:

  • How data becomes insight

  • What separates descriptive, predictive, and prescriptive analytics

  • How machine learning complements traditional statistical methods

This foundation helps you think critically about data and formulate meaningful questions — a key skill in real-world data work.


2. Data Analysis Techniques

Data is rarely clean or perfectly organized. The book introduces the tools and techniques used to:

  • Load, explore, and visualize data

  • Identify patterns, trends, and outliers

  • Prepare data for machine learning workflows

Readers get hands-on experience with common data formats, basic exploratory data analysis, and visualization — turning raw numbers into insights.


3. Introducing Machine Learning

Once the groundwork is laid, the book transitions into core machine learning concepts. You learn:

  • What supervised and unsupervised learning are

  • The differences between classification and regression

  • How common algorithms like linear regression, decision trees, and clustering work

Importantly, explanations are grounded in intuition and reinforced with examples — not just equations.


4. Algorithms and Models

The book explores key machine learning algorithms, explaining:

  • How they make predictions

  • Where they are commonly used

  • What their strengths and limitations are

Simple analogies and clear logic help readers understand not just how algorithms work, but when to use them.


5. Practical Applications

Theory becomes meaningful only when applied to real challenges. The book integrates project-style examples where you learn to build solutions — such as:

  • Predictive models

  • Data-driven dashboards

  • Algorithms for categorization and forecasting

These practical exercises help bridge the gap between learning concepts and applying them to real problems.


6. Tools of the Trade

Data science is powered by tools, and this book introduces common ones that beginners can adopt immediately. You learn:

  • Basics of data handling libraries

  • How to write simple scripts to process and model data

  • Ways to interpret and communicate results

The goal is not to overwhelm with tools, but to make you comfortable with a core set you can expand over time.


Who Should Read This Book?

This introduction is ideal for:

  • Students exploring data science careers

  • Professionals pivoting into analytics or machine learning

  • Self-taught learners seeking practical instruction

  • Anyone who wants to understand data and machine learning without excessive jargon or abstraction

The book is tailored to make learning accessible and meaningful, without assuming prior expertise.


How It Helps You Grow

By the end of the book, readers will have:

  • A solid grasp of essential data science concepts

  • The ability to explore and analyze data

  • Practical understanding of key machine learning algorithms

  • Confidence to tackle simple real-world projects

The emphasis on practical examples and clear explanations makes this an excellent first step for lifelong learners and professionals alike.


Hard Copy: Data Science and Machine Learning for Beginners: A Practical Introduction to Data Analysis, Algorithms, and Real-World Applications

Kindle: Data Science and Machine Learning for Beginners: A Practical Introduction to Data Analysis, Algorithms, and Real-World Applications

Final Thoughts

Starting a career in data science or machine learning can be intimidating, but with the right resources, it becomes an exciting opportunity. Data Science and Machine Learning for Beginners serves as a friendly, structured, and actionable introduction that empowers readers to move from curiosity to competence.

Whether you are just beginning your journey or looking to solidify your foundational skills, this book offers an accessible roadmap into the world of data and intelligent systems.

Advanced Computer Vision with TensorFlow

 


Computer vision is one of the most exciting areas in artificial intelligence. It allows machines to see and understand the visual world — from recognizing objects in images to segmenting scenes and interpreting context. If you already have some foundation in deep learning and want to expand into more sophisticated visual recognition systems, the Advanced Computer Vision with TensorFlow course is an ideal next step.

This intermediate-level online course focuses on practical techniques and models that go beyond basic image classification. You’ll learn how to build and customize systems that can detect, localize, and interpret visual information at a much deeper level.


What the Course Is About

The course teaches advanced computer vision techniques using TensorFlow, a powerful and widely used open-source machine learning framework. It is part of the TensorFlow: Advanced Techniques Specialization, which means the content assumes you already have some experience with Python, neural networks, and basic TensorFlow workflows.

Through hands-on modules, the course guides you from conceptual understanding to real implementation of cutting-edge vision models. You’ll explore topics such as image classification, object detection, image segmentation, and model interpretability.


What You Will Learn

Here’s a snapshot of the key areas the course covers:

Image Classification and Object Localization
You start with a broad overview of computer vision tasks. You’ll revisit classification models, but extend them so that they can localize objects — meaning the model can identify where objects are in the image, not just what they are.

Advanced Object Detection
This module dives into popular object detection architectures like regional-CNN variants and ResNet-based models. You’ll learn to use pre-trained models from TensorFlow Hub, configure them for your datasets, and even train your own detection systems using concepts like transfer learning.

Image Segmentation
Moving beyond bounding boxes, image segmentation assigns a label to every pixel in an image. In this part of the course, you implement models such as fully convolutional networks (FCN), U-Net, and Mask R-CNN. These models help machines understand shapes and boundaries with fine detail.

Model Interpretability and Visualization
Understanding how and why your model makes decisions is crucial in advanced AI. You’ll use methods like class activation maps and saliency maps to visualize internal model behavior and improve architecture design.


Why This Matters

Computer vision is a foundational skill for many real-world applications: autonomous vehicles, medical image analysis, robotics, smart surveillance systems, and augmented reality platforms. This course equips learners with practical, job-relevant skills that go beyond simple model building. You won’t just train models — you’ll customize and interpret them, giving you an edge in both career and research contexts.


How the Learning Experience Works

The course is structured in four modules. Each combines theoretical insights with hands-on coding assignments and practical exercises. Throughout the journey, you’ll work directly with TensorFlow APIs and tools to apply what you’ve learned to real image datasets and projects.

Learners are expected to have intermediate skills — familiarity with Python, basic deep learning, and earlier TensorFlow experience helps you get the most out of this course.


Join Now:Advanced Computer Vision with TensorFlow

Final Thoughts

Whether you’re aiming to build sophisticated AI vision systems or prepare for roles in computer vision engineering, this course provides a solid bridge from foundational knowledge to advanced practice. You’ll learn to build models that see, understand, and interpret visual data, opening doors to careers in machine learning, autonomous systems, and AI research.

Machine Learning

 


Machine learning is one of the most transformative technologies of our time. It powers everything from search engines and recommendations on streaming platforms to medical diagnostics and autonomous vehicles. If you’re interested in stepping into this world, the Machine Learning course on Coursera offers a solid foundation for beginners and aspiring AI practitioners.

This course provides a practical and intuitive introduction to the core concepts, techniques, and tools behind machine learning. It’s designed to help you understand how machines can learn from data, recognize patterns, make predictions, and improve over time — without being explicitly programmed for every scenario.


What This Course Covers

The Machine Learning course walks you through essential topics that form the backbone of modern AI systems. Through a mix of theory and practice, you’ll explore:

Understanding Machine Learning

You begin by learning what machine learning is and how it differs from traditional programming. The course explains how learning from data works and dives into the different ways machines can learn, such as supervised and unsupervised learning. It also introduces examples of how machine learning is used in real-world applications, including speech recognition, recommendation systems, and data-driven decision making.

Supervised Learning Techniques

A large part of the course focuses on supervised learning — where models are trained using labeled data. You’ll learn key algorithms such as linear regression for prediction and logistic regression for classification tasks like separating emails into spam and non-spam. The course also delves into performance evaluation and how to improve models using techniques like feature scaling, regularization, and validation.

Building Models with Python

Hands-on coding assignments teach you how to implement machine learning algorithms in Python using libraries like scikit-learn. These practical exercises help bridge the gap between theory and real implementation. You’ll learn how to split data into training and test sets, preprocess data, train models, evaluate performance, and make predictions — all essential skills for any machine learning practitioner.

Neural Networks and Deep Learning Basics

As you progress, the course introduces the fundamentals of artificial neural networks — the building blocks of deep learning. You’ll learn how these networks mimic the human brain’s way of processing information and how they can be used for more complex tasks such as image and text analysis. This sets the stage for future work in advanced deep learning courses.

Handling Real-World Data

In addition to algorithms, the course emphasizes practical workflows. You’ll learn how to handle real datasets, work with unstructured data such as images and text, and derive actionable insights using machine learning models.


Who This Course Is For

The Machine Learning course is ideal for beginners who already have some basic knowledge of Python, NumPy, and data analysis. It’s structured to be accessible but also deep enough to build a strong conceptual and practical foundation. Whether you want to pursue a career in data science, AI, or analytics, this course gives you the tools and confidence to continue learning more advanced topics.

The curriculum spans several weeks but is self-paced, allowing you to study on your own schedule. You’ll combine video lectures, coding labs, quizzes, and assignments to reinforce your understanding and track your progress.


Why This Course Matters

Machine learning is no longer a niche field. It’s central to modern technology and innovation across industries. Completing this course can open doors to roles in data science, software engineering, AI research, and more. It equips you with a strong conceptual base and practical experience implementing algorithms that power intelligent systems.

By the end of the course, you’ll not only understand how key machine learning models work, but also how to build, evaluate, and apply them to real data. That combination of theory and practice is invaluable for anyone aiming to make an impact in tech or data-driven decision making.

Join Now:Machine Learning

Conclusion

The Machine Learning course serves as an excellent starting point for anyone interested in artificial intelligence and data science. It balances theory with hands-on practice, helping learners not only understand how machine learning works, but also how to apply it to real-world problems.

By completing this course, learners gain the confidence to explore more advanced topics such as deep learning, natural language processing, and computer vision. More importantly, they develop the mindset of a machine learning practitioner — someone who can analyze data, build intelligent models, and use them to make meaningful, informed decisions.

Securing AI Systems

 


Artificial intelligence is reshaping industries and powering systems that influence almost every aspect of modern life. As AI becomes more pervasive, the need to protect these intelligent systems from threats — both digital and algorithmic — is rapidly increasing. The Securing AI Systems course offers an essential learning path for anyone who wants to understand how to safeguard AI applications against real-world risks and vulnerabilities.

This course sits at the intersection of artificial intelligence, machine learning, and cybersecurity, helping learners build a security-first mindset around the design, deployment, and protection of AI systems. Whether you are an AI engineer, data scientist, cybersecurity professional, or a student interested in AI safety, this course equips you with practical skills to protect intelligent systems from attacks and misuse.


What You’ll Learn

The course is structured into several modules focused on equipping learners with both defensive strategies and hands-on experience.

Understanding Threats and Vulnerabilities

You begin by learning about AI security concepts, common attack types, and how adversaries exploit vulnerabilities in models and data. This includes adversarial inputs, data poisoning, and model evasion techniques.

Designing Resilient AI Models

You explore methods for building robust models that can withstand attacks, including adversarial training, testing, and red-teaming practices.

Threat Detection and Incident Response

You learn how to detect attacks on AI systems, monitor for abnormal behavior, and respond to incidents that could compromise system integrity or availability.

Secure Deployment and MLOps

The course addresses how to securely deploy and manage AI systems in production environments, covering access control, monitoring, auditing, and lifecycle management.


Why Securing AI Matters

AI systems increasingly influence financial decisions, healthcare outcomes, transportation, and national infrastructure. If compromised, these systems can cause real-world harm. Securing AI ensures the integrity, confidentiality, and reliability of intelligent applications and protects organizations and users from manipulation, misuse, and unintended consequences.

AI security is not only a technical challenge but also an ethical and organizational responsibility.


Who This Course Is For

This course is well-suited for:

  • AI and machine learning practitioners who want to secure their models

  • Cybersecurity professionals expanding into AI-related risks

  • Data scientists concerned with safe and responsible AI deployment

  • Students and professionals exploring AI governance and safety

A basic understanding of machine learning and Python is helpful.


Career Value

As organizations increasingly adopt AI, professionals who understand both AI development and AI security are in high demand. This course helps build that rare combination of skills, positioning learners for roles in secure AI engineering, AI governance, and advanced cybersecurity.


Join Now:  Securing AI Systems

Conclusion

Securing AI systems is no longer optional — it is a fundamental requirement for responsible and sustainable AI deployment. This course provides a practical foundation for understanding AI risks and building resilient, trustworthy systems.

By completing this course, learners gain the ability to identify vulnerabilities, apply defenses, and ensure that intelligent systems behave reliably and ethically in real-world environments. It is an important step for anyone committed to building AI that is not only powerful, but also safe and secure.


Data Science Capstone

 


In the world of online education, a great course doesn’t just teach theory — it gives you a chance to apply it. That’s exactly what the Data Science Capstone does. Offered as the final course in the Johns Hopkins University Data Science Specialization, this capstone is designed to bring together everything learners have studied and turn it into a real, meaningful project.

Rather than focusing on lectures and quizzes, the course emphasizes building a complete data science solution from start to finish. Learners are challenged to take raw data, explore it, model it, and finally present it in a way that others can understand and use.


What Is the Data Science Capstone?

The Data Science Capstone is a project-based course that simulates a real-world data science problem. Students are expected to work through the entire data science pipeline, beginning with problem understanding and data collection, and ending with a functional data product and a clear presentation of results.

The goal is not just to practice technical skills, but to think like a data scientist: asking the right questions, making informed choices about methods, and communicating insights clearly.


Why This Capstone Is Important

Throughout the specialization, learners gain skills in programming, statistics, data visualization, and machine learning. However, skills become truly valuable only when they are applied together in a realistic setting.

This course allows learners to:

  • Integrate multiple data science techniques into a single project

  • Practice working with messy, real-world data

  • Build and evaluate predictive models

  • Communicate technical results to a non-technical audience

The experience mirrors the expectations of professional data science roles, making it an excellent transition from learning to practice.


How the Course Is Structured

The capstone is organized around a sequence of project milestones:

  1. Understanding the problem and obtaining the data

  2. Performing exploratory data analysis to uncover patterns and insights

  3. Building predictive models based on the data

  4. Improving model performance through refinement and feature engineering

  5. Creating a usable data product, such as an application or dashboard

  6. Developing a presentation to explain the approach and findings

  7. Submitting the project for evaluation and peer feedback

This structure ensures that learners progress in a logical, professional workflow.


Skills You Develop

By the end of the course, learners strengthen both technical and analytical abilities, including:

  • Data cleaning and preprocessing

  • Exploratory analysis and visualization

  • Statistical reasoning and modeling

  • Model evaluation and optimization

  • Data storytelling and presentation

Equally important, learners gain confidence in handling open-ended problems without a single correct answer — a key trait of successful data scientists.


Career and Learning Impact

Completing the Data Science Capstone gives learners a tangible project that can be added to a portfolio or shared with employers. More than that, it provides a sense of what working in data science truly feels like: working with imperfect data, making trade-offs, justifying decisions, and communicating results.

For many students, this is the most valuable part of the entire specialization, because it transforms passive learning into active problem solving.


Join Now: Data Science Capstone

Final Thoughts

The Data Science Capstone is not just a final course — it is a transition point. It marks the shift from learning about data science to actually practicing it. By combining technical skills, analytical thinking, and communication into a single experience, the capstone prepares learners for real-world challenges and professional growth.

Monday, 12 January 2026

Python Coding Challenge - Question with Answer (ID -130126)

 


Let’s explain it step-by-step:

s = {1, 2, 3} s.add([4, 5])
print(s)

 What happens here?

Line 1

s = {1, 2, 3}

A set is created with three integers.


Line 2

s.add([4, 5])

Here you are trying to add a list [4, 5] into a set.

๐Ÿ‘‰ But sets can only store hashable (immutable) objects.

  • int, float, str, tuple → hashable ✅

  • list, dict, set → not hashable

A list is mutable, so Python does not allow it inside a set.

So this line raises an error:

TypeError: unhashable type: 'list'

Line 3

print(s)

This line is never executed, because the program stops at the error in line 2.


Final Output

There is no output — instead you get:

TypeError: unhashable type: 'list'

✅ How to fix it?

If you want to store 4 and 5 as a group inside the set, use a tuple:

s = {1, 2, 3} s.add((4, 5))
print(s)

Output (order may vary):

{1, 2, 3, (4, 5)}

Or if you want to add them as individual elements:

s = {1, 2, 3} s.update([4, 5])
print(s)

Output:

{1, 2, 3, 4, 5}

๐Ÿ”‘ Key Concept

Sets only allow immutable (hashable) elements.
That’s why lists can’t go inside sets — but tuples can 

900 Days Python Coding Challenges with Explanation 

Day 27: Comparing floats directly


 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 27: Comparing Floats Directly

Floating-point numbers can look simple, but comparing them directly is one of the most common Python mistakes—especially for beginners.


❌ The Mistake

a = 0.1 + 0.2
print(a == 0.3) # False ๐Ÿ˜จ

Even though the math looks correct, the comparison fails.


✅ The Correct Way

import math a = 0.1 + 0.2
print(math.isclose(a, 0.3)) # True ✅


❌ Why This Fails?

  • Floats are stored in binary, not decimal

  • Some decimal numbers cannot be represented exactly

  • Small precision errors are introduced

  • Direct equality (==) checks exact matches

  • Results can be unexpected and buggy


๐Ÿง  Simple Rule to Remember

✔ Never compare floats using ==
✔ Use math.isclose() or a tolerance
✔ Think approximate, not exact

Comparing floats safely makes your code more reliable, accurate, and professional ๐Ÿš€

Sunday, 11 January 2026

Python Coding Challenge - Question with Answer (ID -120126)

 


 Step 1: Create the tuple

t = (1, 2, 3)

tuple is immutable → its values cannot be changed.


๐Ÿ”น Step 2: Loop through the tuple

for i in t:

Each element of t is assigned one by one to the variable i:

Loop iterationi value
1st1
2nd2
3rd3

๐Ÿ”น Step 3: Modify i

i = i * 2

This only changes the local variable i, not the tuple.

So:

  • When i = 1 → i becomes 2

  • When i = 2 → i becomes 4

  • When i = 3 → i becomes 6

But t never changes because:

  • You are not assigning back to t

  • And tuples cannot be modified in place


๐Ÿ”น Step 4: Print the tuple

print(t)

Since t was never changed, output is:

(1, 2, 3)

Final Answer

Output:

(1, 2, 3)

Key Concept

PointExplanation
Tuples are immutableTheir values cannot be changed
i is just a copyChanging i does not affect t
No assignment to tSo t stays the same

๐Ÿ”น If you actually want to double the values:

t = tuple(i * 2 for i in t)
print(t)

Output:

(2, 4, 6)

AUTOMATING EXCEL WITH PYTHON

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

 


Code Explanation:

1. Base Class Definition
class Base:

Defines a class named Base.

2. Defining __init_subclass__
    def __init_subclass__(cls):

__init_subclass__ is a special class method.

It is automatically called whenever a subclass of Base is created.

cls refers to the newly created subclass (not the base class).

3. Setting a Class Attribute
        cls.tag = cls.__name__.lower()


Sets a class attribute tag on the subclass.

cls.__name__ → name of the subclass as a string.

.lower() → converts it to lowercase.

So when subclasses are created:

class A(Base) → cls.__name__ is "A" → cls.tag = "a"

class B(Base) → cls.__name__ is "B" → cls.tag = "b"

4. Creating Subclass A
class A(Base): pass

Creates subclass A of Base.

Automatically triggers Base.__init_subclass__(A).

Sets A.tag = "a".

5. Creating Subclass B
class B(Base): pass

Creates subclass B of Base.

Automatically triggers Base.__init_subclass__(B).

Sets B.tag = "b".

6. Printing the Tags
print(A.tag, B.tag)

Prints the class attributes assigned during subclass creation.

7. Final Output
a b

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

 


Code Explanation:

1. Class Definition
class A:

This defines a new class named A.

2. Overriding __setattr__ Method
    def __setattr__(self, k, v):


__setattr__ is a special method in Python.

It is automatically called whenever an attribute is assigned to an object.

Parameters:

self → the object itself

k → name of the attribute being assigned

v → value being assigned

3. Custom Attribute Assignment
        super().__setattr__(k, v * 2)


Calls the parent class (object) __setattr__ method.

Instead of storing v, it stores v * 2.

This means every value assigned to an attribute will be doubled before storage.

4. Creating an Object
a = A()

Creates an instance a of class A.

5. Assigning an Attribute
a.x = 3

Triggers A.__setattr__(a, 'x', 3)

Inside __setattr__, value becomes 3 * 2 = 6

So internally:

a.x = 6

6. Printing the Attribute
print(a.x)

Prints the stored value of x, which is 6.

7. Final Output
6

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

 



Code Explanation:

1. Defining Class A
class A:
    def f(self): return "A"

A class A is defined.

It has a method f() that returns "A".

2. Defining Class B
class B:
    def f(self): return "B"

A class B is defined.

It also has a method f() but returns "B".

3. Defining Class C Inheriting from A
class C(A): pass

C initially inherits from A.

So normally:

C().f() → "A"

4. Changing the Base Class at Runtime
C.__bases__ = (B,)

This dynamically changes the inheritance of class C.

Now C no longer inherits from A, but from B.

So the new hierarchy is:

C → B → object

5. Calling f() on a C Object
print(C().f())

Step-by-step:

C() creates an instance of C.

f() is searched:

Not found in C

Found in B (new base class)

B.f() is called → returns "B".

6. Final Output
B

Final Answer
✔ Output:
B

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


Code Explanation:

1. Creating a Registry List
registry = []

An empty list named registry is created.

It will store the names of all subclasses of Plugin.

2. Defining the Base Class
class Plugin:

A base class named Plugin is defined.

It will automatically track all its subclasses.

3. Overriding __init_subclass__
    def __init_subclass__(cls):
        registry.append(cls.__name__)


__init_subclass__ is a special hook called every time a subclass is created.

cls refers to the newly created subclass.

The subclass name is appended to the registry list.

4. Creating Subclass A
class A(Plugin): pass


A is created as a subclass of Plugin.

This triggers:

Plugin.__init_subclass__(A)


"A" is appended to registry.

5. Creating Subclass B
class B(Plugin): pass

B is created as a subclass of Plugin.

This triggers:

Plugin.__init_subclass__(B)

"B" is appended to registry.

6. Printing the Registry
print(registry)

Prints the contents of registry.

7. Final Output
['A', 'B']

Final Answer
✔ Output:
['A', 'B']
 

800 Days Python Coding Challenges with Explanation

Day 26: Using time.sleep() in Async Code

 

๐Ÿ Python Mistakes Everyone Makes ❌

Day 26: Using time.sleep() in Async Code

Async code is powerful—but one small mistake can completely block it.


❌ The Mistake

import time async def task(): print("Start") time.sleep(2)
print("End")

Looks harmless, right?
But this breaks async behavior.


๐Ÿค” Why This Is a Problem

  • time.sleep() blocks the entire event loop

  • No other async tasks can run during the sleep

  • Your “async” code becomes sync and slow

In async code, blocking = ๐Ÿšซ performance.


✅ The Correct Way

Use asyncio.sleep() instead:

import asyncio async def task(): print("Start") await asyncio.sleep(2)
print("End")

This pauses without blocking, allowing other tasks to run.


❌ Why the Mistake Is Dangerous

  • Freezes concurrent tasks

  • Ruins scalability

  • Causes confusing performance issues

  • Defeats the purpose of async programming


๐Ÿง  Simple Rule to Remember

✔ Never use time.sleep() in async code
✔ Always use await asyncio.sleep()
✔ Blocking calls don’t belong in async functions

๐Ÿ Async rule: If it blocks, it doesn’t belong in async def.

Day 25: Wrong Use of or in Conditions

 

Day 25: Wrong Use of or in Conditions

This is a classic Python gotcha that trips up beginners and even experienced developers.


❌ The Mistake

x = 3 if x == 1 or 2:
print("x is 1 or 2")

You might expect this to run only when x is 1 or 2…
But it always runs, no matter what x is.


๐Ÿค” Why This Happens

Python reads the condition like this:

if (x == 1) or (2):
  • x == 1 → True or False

  • 2 → always True (non-zero values are truthy)

So the whole condition is always True.


✅ The Correct Way

Option 1: Compare explicitly

if x == 1 or x == 2: print("x is 1 or 2")

Option 2 (Recommended): Use in

if x in (1, 2):
print("x is 1 or 2")

Cleaner, safer, and more Pythonic ✅


❌ Why the Mistake Is Dangerous

  • Conditions behave incorrectly

  • Bugs are hard to notice

  • Logic silently fails

  • Leads to unexpected program flow


๐Ÿง  Simple Rule to Remember

✔ or does not repeat comparisons
✔ Use in for multiple equality checks
✔ If it reads like English, it’s probably wrong ๐Ÿ˜„

# Think like Python, not English if x in (1, 2):
...

๐Ÿ Pro tip: When checking multiple values, in is almost always the best choice.

Python Coding Challenge - Question with Answer (ID -110126)

+
 

Explanation:

Initialization
s = 0

Creates a variable s and initializes it with 0.

This variable will store the running sum.

Loop Start
for i in range(1, 6):

Loop runs with values of i from 1 to 5.

So the loop will run for:

i = 1, 2, 3, 4, 5

Condition to Skip i = 3
if i == 3:

Checks if the current value of i is 3.

continue

If i is 3, the loop skips the remaining code and moves to the next iteration.

So when i = 3, no addition and no print happen.

Add i to s
s += i

Adds current i value to s.

Condition to Skip if Sum Exceeds 6
if s > 6:

Checks if the current sum s is greater than 6.

continue

If s > 6, printing is skipped.

Printing the Sum
print(s)

Prints the value of s only if it passed both conditions.

Iteration-Wise Execution

Iteration i i == 3? s after add s > 6? Printed
1 1 No 1 No 1
2 2 No 3 No 3
3 3 Yes → skipped
4 4 No 7 Yes → skipped
5 5 No 12 Yes → skipped

Final Output
1
3

PYTHON LOOPS MASTERY



Saturday, 10 January 2026

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

 


Code Explanation:

1. Defining a Custom Metaclass
class Meta(type):

Meta is a metaclass because it inherits from type.

A metaclass controls how classes create their instances.

2. Overriding the Metaclass __call__ Method
    def __call__(cls, *a, **k):
        obj = super().__call__(*a, **k)
        obj.ready = True
        return obj


__call__ is invoked when a class is called to create an instance (Task()).

Steps:

Calls super().__call__() → creates the object normally.

Adds a new attribute ready = True to the object.

Returns the modified object.

So every object created using this metaclass automatically has ready = True.

3. Defining a Class Using the Metaclass
class Task(metaclass=Meta):
    pass

Task is created using Meta as its metaclass.

Task() will invoke Meta.__call__.

 4. Creating an Instance
t = Task()

This triggers:

Meta.__call__(Task)


Inside __call__:

A new Task object is created.

t.ready = True is added.

5. Checking the Attribute
print(hasattr(t, "ready"))

Checks if attribute "ready" exists on t.

Since Meta.__call__ added it, result is True.

6. Final Output
True

Final Answer
✔ Output:
True

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

 


Code Explanation:

1. Defining the Class
class Safe:

A class named Safe is defined.

2. Overriding __getattribute__
    def __getattribute__(self, name):
        if name == "open":
            return super().__getattribute__(name)
        return "blocked"

__getattribute__ is called for every attribute access on an instance.

It receives:

self → the instance

name → the name of the attribute being accessed

Logic:

If the attribute name is "open", delegate to Python’s normal lookup using super().__getattribute__.

For any other attribute, return the string "blocked" instead of the real value.

So:

s.open → real method

s.x, s.anything_else → "blocked"

3. Defining the open Method
    def open(self):
        return "ok"

A normal instance method that returns "ok".

4. Creating an Object
s = Safe()

Creates an instance of Safe.

5. Accessing Attributes
print(s.open(), s.x)

Let’s evaluate each part:

▶ s.open()

s.open triggers __getattribute__(s, "open").

Since name == "open", it calls super().__getattribute__("open").

That returns the actual method open.

() calls it → returns "ok".

▶ s.x

s.x triggers __getattribute__(s, "x").

"x" ≠ "open", so it returns "blocked".

No error is raised.

6. Final Output
ok blocked

Final Answer
✔ Output:
ok blocked

Python Coding Challenge - Question with Answer (ID -100126)

 


Explanation:

1. Function Definition
def make_filter(limit, seen=[]):

What happens:

Defines a function make_filter.

Takes:

limit → a threshold value.

seen → a mutable default list shared across calls.

Important: seen is created once when the function is defined, not each time it is called.

2. Returning a Lambda Function
return lambda x: x > limit and not seen.append(x)

This returns a function that:

Checks if x > limit

Appends x to seen

Uses not to invert the return value of seen.append(x)

Since:

seen.append(x) → returns None
not None → True

So the lambda returns:

True if x > limit

False otherwise

But it also mutates the seen list.

3. Creating the Filter Function
f = make_filter(2)

This means:

limit = 2

seen = [] (shared list)

f is now:

lambda x: x > 2 and not seen.append(x)

4. Applying filter
filter(f, [1,2,3,4,3,5])

5. Why duplicates are not removed

Because:

seen.append(x) is always executed for x > limit.

No check is done to prevent duplicates.

The lambda only tests x > limit.

So every value > 2 passes, including repeated 3.

6. Final Output
print(list(filter(f, [1,2,3,4,3,5])))

Output:

[3, 4, 3, 5]

Final Answer
[3, 4, 3, 5]

Python for GIS & Spatial Intelligence

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (207) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (8) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (29) data (1) Data Analysis (26) Data Analytics (20) data management (15) Data Science (299) Data Strucures (16) Deep Learning (123) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (62) Git (9) Google (48) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (249) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1258) Python Coding Challenge (1042) Python Mistakes (50) Python Quiz (428) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)