Showing posts with label Python Coding Challenge. Show all posts
Showing posts with label Python Coding Challenge. Show all posts

Wednesday, 18 March 2026

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

 


Code Explanation:

1️⃣ Importing the Module

import threading

Explanation

Imports Python’s threading module.

Used to create and manage threads.

2️⃣ Defining the Function
def task():

Explanation

A function named task is defined.

This function will be executed inside a thread.

3️⃣ Function Body
print("X")

Explanation

When the thread runs, it prints:

X

4️⃣ Creating the Thread
t = threading.Thread(target=task)

Explanation

A thread object t is created.

target=task → thread will execute the task() function.

Thread is created but not started yet.

5️⃣ Starting the Thread
t.start()

Explanation

Starts the thread.

The thread executes task() and prints:

X

6️⃣ Waiting for Thread Completion
t.join()

Explanation

join() makes the main program wait until thread finishes.

Ensures that "X" is printed before moving forward.

7️⃣ Starting the Thread Again (ERROR)
t.start()

Explanation

This tries to start the same thread again.

❌ In Python, a thread can be started only once.

Once a thread finishes execution, it cannot be restarted.

❌ Runtime Error
RuntimeError: threads can only be started once

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

 


Code Explanation:

1️⃣ Importing the Module
import threading

Explanation

Imports the threading module.

Enables creation and management of multiple threads.

2️⃣ Creating an Empty List
threads = []

Explanation

A list named threads is created.

It will store all thread objects so we can later wait for them using join().

3️⃣ Starting the Loop
for i in range(3):

Explanation

Loop runs 3 times.

Values of i:

0, 1, 2

4️⃣ Creating the Thread (Important)
t = threading.Thread(target=lambda: print(i))

Explanation

A new thread is created.

target=lambda: print(i) means:

Each thread will execute a lambda function that prints i.

⚠️ Critical Concept: Late Binding

The lambda does NOT capture the value of i at that moment.

Instead, it captures the reference to variable i.

By the time threads execute, loop has finished → i = 2.

๐Ÿ‘‰ So all threads will use the same final value of i.

5️⃣ Storing the Thread
threads.append(t)

Explanation

Thread is added to the list.

This helps later to join all threads.

6️⃣ Starting the Thread
t.start()

Explanation

Starts execution of the thread.

The lambda function will run concurrently.

7️⃣ Joining All Threads
for t in threads:
    t.join()

Explanation

Ensures the main program waits for all threads to finish.

Prevents premature program exit.

๐Ÿ“ค Final Output
2
2
2

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

 


 Code Explanation:

1. Importing the Module
import threading
๐Ÿ” Explanation:

Imports Python’s built-in threading module

This module allows you to run multiple functions concurrently

๐Ÿ“Œ 2. Defining the Task Function
def task():
    print("A")
๐Ÿ” Explanation:

A function named task is created

It simply prints "A"

This function will run inside a separate thread

๐Ÿ“Œ 3. Creating a Thread
t = threading.Thread(target=task)
๐Ÿ” Explanation:

Creates a new thread object t

target=task means:
๐Ÿ‘‰ “Run the task function inside this thread”

๐Ÿ“Œ 4. Starting the Thread
t.start()
๐Ÿ” Explanation:

Starts the thread execution

The task() function begins running in parallel

Now:

Main program continues

Thread runs independently

๐Ÿ“Œ 5. Main Thread Execution
print("B")
๐Ÿ” Explanation:

This runs in the main thread

Prints "B"


Possible outputs:
A
B

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

 


Code Explanation:

1️⃣ Importing the Module

import threading

Explanation

Imports Python’s threading module.

This module allows execution of multiple threads simultaneously.

2️⃣ Defining the Function
def task(n):

Explanation

A function named task is defined.

It takes one argument n.

Each thread will call this function with a different value.

3️⃣ Printing the Value
print(n)

Explanation

This prints the value passed to the function.

Each thread will print its own number.

4️⃣ Loop Creation
for i in range(3):

Explanation

Loop runs 3 times.

Values of i will be:

0, 1, 2

5️⃣ Creating and Starting Threads
threading.Thread(target=task, args=(i)).start()

Explanation (VERY IMPORTANT ⚠️)

✔ Thread Creation

threading.Thread(...) creates a new thread.

target=task → thread will run task() function.

❌ Mistake in Arguments

args=(i) is NOT a tuple.

Python treats (i) as just an integer, not a tuple.

๐Ÿ‘‰ Correct tuple should be:

args=(i,)
⚠️ What Happens Due to Mistake?

Thread expects arguments as an iterable (tuple/list).

But (i) is an int, not iterable.

So Python raises an error.

❌ Runtime Error
TypeError: 'int' object is not iterable

Final Output:
Error

Monday, 16 March 2026

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

 


Code Explanation:

1️⃣ Importing the Threading Module
import threading

Explanation

This line imports Python’s threading module.

The module allows a program to run multiple threads (tasks) concurrently.

Threads help perform operations simultaneously within the same process.

2️⃣ Creating a Global Variable
x = 5

Explanation

A variable x is created with the value 5.

This variable is defined outside any function, so it is a global variable.

Global variables can be accessed by all parts of the program.

3️⃣ Defining the Function
def change():

Explanation

A function named change is defined.

This function will later be executed inside a separate thread.

4️⃣ Declaring a Global Variable Inside the Function
global x

Explanation

This tells Python that the variable x inside the function refers to the global variable.

Without global, Python would treat x as a local variable.

5️⃣ Changing the Value of the Variable
x = 10

Explanation

The function changes the value of global variable x from 5 to 10.

6️⃣ Creating a Thread
t = threading.Thread(target=change)

Explanation

A Thread object is created and stored in variable t.

target=change means the thread will run the change() function.

At this stage, the thread is created but not started.

7️⃣ Starting the Thread
t.start()

Explanation

This starts the thread.

The thread begins executing the change() function.

Inside the thread, the value of x becomes 10.

8️⃣ Waiting for the Thread to Finish
t.join()

Explanation

join() tells the main thread to wait until the thread t completes its work.

This ensures that the value of x is updated before printing.

9️⃣ Printing the Value
print(x)

Explanation

The program prints the value of x.

Since the thread changed x to 10, the printed value is:

10

๐Ÿ“ค Final Output
10

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

 


Code Explanation:

1️⃣ Importing Module
import threading

Explanation

This line imports the threading module.

The threading module allows Python to run multiple threads (tasks) concurrently.

Threads help execute parts of a program simultaneously.

2️⃣ Defining the Function
def task():

Explanation

A function named task is created.

This function will be executed inside a separate thread.

3️⃣ Loop Inside the Function
for i in range(2):

Explanation

A loop runs 2 times.

range(2) generates numbers:

0, 1

4️⃣ Printing Values
print(i)

Explanation

Each iteration prints the value of i.

So the function prints:

0
1

5️⃣ Creating a Thread
t = threading.Thread(target=task)

Explanation

A Thread object is created.

target=task means the thread will execute the task() function.

At this point, the thread is created but not started yet.

6️⃣ Starting the Thread
t.start()

Explanation

This starts the thread.

The thread begins executing the task() function.

The function prints:

0
1

7️⃣ Waiting for Thread to Finish
t.join()

Explanation

join() tells the main program to wait until the thread finishes.

Without join(), the program might print "Done" before the thread finishes.

8️⃣ Printing Final Statement
print("Done")

Explanation

After the thread finishes, the main program prints:

Done

๐Ÿ“ค Final Output
0
1
Done

Thursday, 12 March 2026

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

 


Code Explanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a template used to create objects (instances).

2. Defining Method f
def f(self):
    return "method"

Explanation:

A method named f is defined inside class A.

self refers to the object (instance) that calls the method.

The method returns the string "method".

So initially:

A.f() → "method"

If called through an object:

a.f() → "method"

3. Creating an Object
a = A()

Explanation:

This creates an object a of class A.

The object can access the class method f.

Example:

a.f() → "method"

4. Assigning a New Function to a.f
a.f = lambda: "instance"

Explanation:

This line creates an instance attribute f for object a.

It assigns a lambda function that returns "instance".

Lambda function:

lambda: "instance"

Important concept:

Instance attributes override class methods with the same name.

So now the object a has:

a.__dict__ = {'f': <lambda>}

Meaning:

a.f → instance function

The class method A.f still exists but is hidden for this object.

5. Calling a.f()
print(a.f())

Explanation:

Python searches attributes in this order:

Instance attributes

Class attributes

Parent classes

Since a already has an instance attribute f, Python uses that instead of the class method.

So Python executes:

lambda: "instance"

Which returns:

"instance"

6. Final Output
instance

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


Code Explanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a blueprint used to create objects (instances).

2. Creating a Class Variable count
count = 0

Explanation:

count is a class variable.

It belongs to the class A, not to individual objects.

All objects of class A share this same variable.

Initial value:

A.count = 0

3. Defining the __call__ Method
def __call__(self):

Explanation:

__call__ is a special (magic) method in Python.

It allows an object to be called like a function.

Example:

a()

Python internally runs:

a.__call__()

4. Increasing the Counter
A.count += 1

Explanation:

Each time the object is called, the class variable count increases by 1.

Since count belongs to the class, all objects share the same counter.

Example:

A.count = A.count + 1

5. Returning the Updated Value
return A.count

Explanation:

After increasing the counter, the method returns the updated value.

6. Creating Object a
a = A()

Explanation:

This creates an instance a of class A.

Object a can now be called like a function because of __call__.

7. Creating Object b
b = A()

Explanation:

This creates another instance b of class A.

Both a and b share the same class variable count.

8. Calling the Objects
print(a(), b(), a())

Python executes the calls from left to right.

8.1 First Call: a()

Python runs:

a.__call__()

Steps:

A.count = 0 + 1
A.count = 1

Return value:

1

8.2 Second Call: b()

Python runs:

b.__call__()

Steps:

A.count = 1 + 1
A.count = 2

Return value:

2

8.3 Third Call: a()

Python runs again:

a.__call__()

Steps:

A.count = 2 + 1
A.count = 3

Return value:

3

9. Final Output

The print statement prints:

1 2 3


Wednesday, 11 March 2026

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

 


Code Explanation:

1. Defining Class D
class D:

Explanation:

This line creates a class named D.

This class will act as a descriptor.

A descriptor is a class that defines special methods like __get__, __set__, or __delete__ to control attribute access.

2. Defining the __get__ Method
def __get__(self, obj, objtype):

Explanation:

__get__ is a descriptor method.

It is automatically called when the attribute is accessed (read).

Parameters:

self → descriptor object (D)

obj → instance of class A

objtype → the class (A)

When we access a.x, Python internally calls:

D.__get__(descriptor, a, A)
3. Returning a Value
return 50

Explanation:

Whenever x is accessed through an object, this method returns 50.

So the descriptor controls the value returned.

Meaning:

a.x → 50
4. Defining Class A
class A:

Explanation:

This creates another class named A.

5. Creating Descriptor Attribute
x = D()

Explanation:

Here an object of class D is assigned to attribute x.

This makes x a descriptor attribute.

Accessing x will trigger the __get__ method.

So:

A.x → descriptor object of class D
6. Creating an Object
a = A()

Explanation:

This creates an instance a of class A.

7. Adding Attribute Directly to Object Dictionary
a.__dict__['x'] = 20

Explanation:

__dict__ stores all instance attributes of an object.

This line manually adds an attribute:

x = 20

inside the object's dictionary.

So internally:

a.__dict__ = {'x': 20}

8. Printing a.x
print(a.x)

Explanation:

Python checks attributes in this order:

Data descriptor (__get__ + __set__)

Instance dictionary

Non-data descriptor (__get__ only)

Class attributes

Here:

D defines only __get__, so it is a non-data descriptor.

Python first checks instance dictionary.

It finds:

a.__dict__['x'] = 20

So Python returns 20 instead of calling the descriptor.

9. Final Output
20

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

 


Code Esxplanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a blueprint used to create objects (instances).

2. Defining Method f
def f(self):
    return "A"

Explanation:

A method f is defined inside class A.

self refers to the instance (object) of the class.

The method returns the string "A".

So initially:

A.f() → returns "A"

3. Creating an Object
a = A()

Explanation:

This creates an object a of class A.

The object a can access the method f.

Example:

a.f() → "A"

4. Replacing the Method f
A.f = lambda self: "B"

Explanation:

This line replaces the method f of class A.

A lambda function is assigned to A.f.

Lambda function:

lambda self: "B"

means:

It takes self as an argument.

It returns "B".

Now the original method is overwritten.

So now:

A.f() → returns "B"

5. Calling the Method
print(a.f())

Explanation:

The object a looks for method f.

Python finds f in the class A.

Since we replaced it with the lambda function, Python executes:

lambda self: "B"

with self = a.

So it returns:

"B"

6. Final Output
B
Key Concept
Methods Can Be Changed Dynamically

In Python, class methods can be modified after class creation.

Flow in this code:

Original method: f() → "A"
A.f replaced by lambda
New method: f() → "B"

✅ Final Output

B

Tuesday, 10 March 2026

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

 


Code Explanation:

1. Defining Class A

class A:

    data = []

Explanation:

class A: creates a class named A

data = [] defines a class variable named data.

It is an empty list.

Class variables are shared by the class and its subclasses unless overridden.

So initially:

A.data → []


2. Defining Subclass B

class B(A):

    pass

Explanation:

class B(A): means B inherits from class A.

pass means no new attributes or methods are added.

Since B does not define its own data, it inherits data from A.

So:

B.data → refers to A.data

3. Defining Subclass C

class C(A):

    data = []

Explanation:

class C(A): means C also inherits from class A.

But here data = [] creates a new class variable inside C.

This overrides the inherited variable from A.

So now:

A.data → []

B.data → refers to A.data

C.data → []  (separate list)

4. Modifying B.data

B.data.append(1)

Explanation:

B.data refers to A.data because B inherited it.

.append(1) adds 1 to the list.

Since B and A share the same list, the change affects both.

After this operation:

A.data → [1]

B.data → [1]

But:

C.data → []

because C has its own separate list.

5. Printing the Values

print(A.data, B.data, C.data)

Explanation:

A.data → [1]

B.data → [1] (same list as A)

C.data → [] (different list)

6. Final Output

[1] [1] []

Key Concept

Class Variable Inheritance

Class data value Reason

A [1] Original list modified

B [1] Inherited from A

C [] Overridden with its own list


✅ Final Output

[1] [1] []


900 Days Python Coding Challenges with Explanation

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

 


Code Explanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a blueprint used to create objects (instances).

2. Defining Method f
def f(self):
    return 1

Explanation:

A method named f is defined inside class A.

self refers to the current object (instance) of the class.

The method simply returns the value 1 when called.

So the method behavior is:

f(self) → returns 1

3. Creating an Object
a = A()

Explanation:

This creates an instance (object) a of class A.

Now the object a can access the method f.

Example:

a.f()

4. Print Statement
print(A.f(a), a.f())

This statement contains two function calls.

5. First Call: A.f(a)

Explanation:

Here we call method f using the class name.

When calling a method from the class, we must manually pass the object as the argument.

So Python executes:

A.f(a)

Which is equivalent to:

f(self=a)

Inside the function:

return 1

So:

A.f(a) → 1

6. Second Call: a.f()

Explanation:

Here we call the method using the object a.

Python automatically passes the object as self.

Internally Python converts:

a.f()

into:

A.f(a)

So the method runs and returns:

1

Thus:

a.f() → 1

7. Final Output

The print statement prints both values:

print(1, 1)

So the output is:

1 1

Monday, 9 March 2026

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

 


Code Explanation:

1. Defining Class D
class D:

Explanation:

This line defines a class named D.

This class will act as a descriptor.

A descriptor is a class that defines methods like __get__, __set__, or __delete__ to control attribute access.

2. Defining __get__ Method
def __get__(self, obj, objtype):

Explanation:

__get__ is a descriptor method.

It is automatically called when the attribute is accessed (read).

Parameters:

self → the descriptor object (D)

obj → the instance of class A

objtype → the class A

Example call when a.x is accessed:

D.__get__(descriptor, a, A)

3. Returning the Value
return obj._x

Explanation:

This returns the value stored in the instance variable _x.

The descriptor redirects access to _x inside the object.

So:

a.x → returns a._x

4. Defining __set__ Method
def __set__(self, obj, value):

Explanation:

__set__ is another descriptor method.

It is automatically called when the attribute is assigned a value.

Example when writing:

a.x = 5

Python internally calls:

D.__set__(descriptor, a, 5)

Parameters:

self → descriptor object

obj → instance of A

value → value being assigned

5. Modifying the Value Before Storing
obj._x = value * 2

Explanation:

Instead of storing the value directly, it multiplies the value by 2.

Then it stores it in obj._x.

So when:

a.x = 5

It becomes:

a._x = 10

6. Defining Class A
class A:

Explanation:

This creates another class named A.

7. Creating Descriptor Attribute
x = D()

Explanation:

Here an object of class D is assigned to attribute x.

This makes x a descriptor attribute.

Any access to x will trigger __get__ or __set__.

So:

A.x → descriptor object of class D

8. Creating an Object
a = A()

Explanation:

This creates an instance a of class A.

9. Assigning Value to x
a.x = 5

Explanation:

Since x is a descriptor, Python calls:

D.__set__(descriptor, a, 5)

Inside __set__:

obj._x = value * 2

So:

a._x = 5 * 2
a._x = 10

10. Accessing x
print(a.x)

Explanation:

Python calls:

D.__get__(descriptor, a, A)

Inside __get__:

return obj._x

Since:

a._x = 10

It returns 10.

11. Final Output
10

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

 


Code Explanation:

1. Defining Class A

class A:

Explanation:

This line defines a class named A.

A class is a template used to create objects.

2. Defining __getattribute__ Method

def __getattribute__(self, name):

Explanation:

__getattribute__ is a special (magic) method in Python.

It is automatically called every time any attribute of an object is accessed.

self → the current object

name → the attribute name being accessed.

Example:

When we write a.x, Python internally calls:

a.__getattribute__("x")

3. Checking if Attribute Name is "x"

if name == "x":

    return 10

Explanation:

If the attribute being accessed is x, the method returns 10.

This means any access to a.x will return 10, even if x is not defined.

So:

a.x → 10

4. Accessing Default Attribute Behavior

return super().__getattribute__(name)

Explanation:

If the attribute is not "x", Python calls the parent class implementation of __getattribute__.

super() refers to the base object behavior.

This line tells Python to look for the attribute normally.

If the attribute exists → return it.

If it does not exist → Python will trigger __getattr__.

5. Defining __getattr__

def __getattr__(self, name):

    return 20

Explanation:

__getattr__ is another special method.

It is called only when the attribute is not found normally.

It returns 20 for any missing attribute.

So if an attribute does not exist, Python returns:

20

6. Creating an Object

a = A()

Explanation:

This creates an object a of class A.

7. Printing Attributes

print(a.x, a.y)

Python evaluates this in two parts.

7.1 Accessing a.x

Python calls:

a.__getattribute__("x")

Inside __getattribute__:

name == "x" → True

Returns 10

So:

a.x → 10

7.2 Accessing a.y

Python calls:

a.__getattribute__("y")

Inside __getattribute__:

name == "x" → False

Calls:

super().__getattribute__("y")

But y does not exist in the object.

So Python calls:

__getattr__("y")

This returns:

20

So:

a.y → 20

8. Final Output

10 20


900 Days Python Coding Challenges with Explanation

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

 


Code Explanation:

1. Defining Class A
class A:

Explanation:

This line creates a class named A.

A class is a blueprint for creating objects.

2. Defining Method f
def f(self):
    return "A"

Explanation:

A method f is defined inside class A.

self refers to the current object (instance) of the class.

The method returns the string "A" when called.

So the class now contains a method:

A.f() → returns "A"

3. Creating an Object
a = A()

Explanation:

This creates an object a of class A.

Now a can access the class methods and attributes.

Example:

a.f()  → "A"

4. Assigning a New Attribute to the Object
a.f = "value"

Explanation:

Here we assign "value" to a.f.

This creates an instance attribute f inside object a.

In Python, instance attributes override class attributes or methods with the same name.

So now:

a.f → "value"

The original method f in class A is shadowed (hidden) by the instance variable.

5. Printing the Value
print(a.f)

Explanation:

Python first looks for attribute f inside the object a.

It finds a.f = "value".

Therefore it prints "value", not the method.

6. Final Output
value

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

 


Code Explanation:

1. Defining Class A
class A:
    data = []

Explanation:

class A: creates a class named A.

Inside the class, a variable data is defined.

data = [] creates an empty list.

This list is a class variable, not an instance variable.

A class variable is shared by the class and all its subclasses and objects unless overridden.

So currently:

A.data → []

2. Creating Subclass B
class B(A):
    pass

Explanation:

class B(A): means B inherits from A.

pass means the class has no additional code.

Since B inherits from A, it also has access to A.data.

So:

B.data → refers to A.data

3. Creating Subclass C
class C(A):
    pass

Explanation:

class C(A): means C also inherits from A.

pass means nothing new is added.

C also inherits the class variable data from A.

So:

C.data → refers to A.data

4. Modifying the List Through B
B.data.append(10)

Explanation:

B.data refers to A.data because B inherited it.

.append(10) adds 10 to the list.

Since the list is shared, the change affects A.data and C.data as well.

Now the list becomes:

A.data → [10]
B.data → [10]
C.data → [10]

5. Printing the Values
print(A.data, C.data)

Explanation:

A.data prints the class variable of A.

C.data also refers to the same list inherited from A.

Since the list was modified earlier, both show the same value.

Final Output
[10] [10]

Saturday, 7 March 2026

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

 


Code Explanation:

๐Ÿ”น 1️⃣ Defining Class A
class A:

Creates a class named A.

Objects created from this class will inherit its methods and attributes.

๐Ÿ”น 2️⃣ Defining the __getattr__ Method
def __getattr__(self, name):
    return name.upper()

This method is automatically called when Python cannot find an attribute normally.

Parameters:

self → the object

name → the attribute name being accessed

Behavior here:

It converts the attribute name to uppercase and returns it.

Example:

a.test → "TEST"

๐Ÿ”น 3️⃣ Creating an Object
a = A()

Creates an instance named a.

At this moment:

a.__dict__ = {}

The object has no attributes defined.

๐Ÿ”น 4️⃣ Accessing Missing Attributes
print(a.test + a.python)

Python evaluates each attribute separately.

๐Ÿ”น Step 1: Accessing a.test

Python lookup order:

1️⃣ Check instance dictionary

a.__dict__

No test found.

2️⃣ Check class attributes

A.__dict__

No test.

3️⃣ Check parent classes

Still not found.

4️⃣ Python calls:

__getattr__(a, "test")

Inside the method:

return "TEST"

So:

a.test → "TEST"
๐Ÿ”น Step 2: Accessing a.python

Again Python cannot find the attribute.

So it calls:

__getattr__(a, "python")

Inside the method:

return "PYTHON"

So:

a.python → "PYTHON"
๐Ÿ”น Step 3: String Concatenation
"TEST" + "PYTHON"

Result:

"TESTPYTHON"

✅ Final Output
TESTPYTHON

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

 


Code Explanation:

๐Ÿ”น 1️⃣ Defining Class A
class A:

Creates a class named A.

Objects created from this class will inherit its attributes.

๐Ÿ”น 2️⃣ Defining a Class Variable
data = []

data is a class variable.

It belongs to the class A, not to individual objects.

Internally Python stores:

A.data = []

This single list will be shared by all instances.

๐Ÿ”น 3️⃣ Creating First Object
a = A()

Creates an instance named a.

At this moment:

a.__dict__ = {}

The object has no instance attributes yet.

But it can access:

A.data
๐Ÿ”น 4️⃣ Creating Second Object
b = A()

Creates another instance b.

Now:

a.__dict__ = {}
b.__dict__ = {}

Both objects still refer to the same class variable:

A.data
๐Ÿ”น 5️⃣ Modifying the List Through a
a.data.append(5)

Python does attribute lookup:

1️⃣ Check instance dictionary

a.__dict__

No data found.

2️⃣ Check class attributes

A.data

Found the list.

So Python runs:

A.data.append(5)

The list becomes:

[5]

Since the list belongs to the class, the change affects all objects.

๐Ÿ”น 6️⃣ Printing b.data
print(b.data)

Lookup order:

1️⃣ Check instance dictionary

b.__dict__

No data.

2️⃣ Check class attributes

A.data

Found the list:

[5]
✅ Final Output
[5]

Thursday, 5 March 2026

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

 



Code Explanation:

๐Ÿ”น 1️⃣ Defining Class A
class A:

Creates a class named A.

Objects created from this class will inherit its attributes.

๐Ÿ”น 2️⃣ Defining a Class Variable
x = 5

x is a class variable.

It belongs to the class A, not to individual objects.

Internally:

A.x = 5

All objects can access it unless they override it.

๐Ÿ”น 3️⃣ Creating the First Object
a = A()

Creates an instance named a.

At this moment:

a.__dict__ = {}

The object has no instance attributes yet.

But it can access:

A.x

๐Ÿ”น 4️⃣ Creating the Second Object
b = A()

Creates another instance named b.

Same situation:

b.__dict__ = {}

No instance attributes yet.

๐Ÿ”น 5️⃣ Assigning a Value to a.x
a.x = 20

This is the most important line.

Python does NOT modify the class variable.

Instead it creates an instance variable inside object a.

Internally:

a.__dict__ = {'x': 20}

Now:

a.x → instance attribute
A.x → class attribute

The class variable remains unchanged.

๐Ÿ”น 6️⃣ Printing Values
print(A.x, b.x, a.x)

Now Python evaluates each part.

Step 1: A.x

Accessing the class variable directly:

A.x → 5
Step 2: b.x

Lookup order:

1️⃣ Check instance dictionary

b.__dict__

No x found.

2️⃣ Check class attributes

A.x

Found:

5

So b.x = 5.

Step 3: a.x

Lookup order:

1️⃣ Instance dictionary

a.__dict__ = {'x': 20}

Found immediately.

So Python returns:

20


✅ Final Output
5 5 20

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

 


Code Explanation:

1️⃣ Defining Class A
class A:

Creates a class named A.

All objects created from this class will use its attributes and methods.

๐Ÿ”น 2️⃣ Defining a Class Attribute
x = 10

x is a class variable.

It belongs to the class A, not to individual objects.

Any instance can access it unless overridden.

So internally:

A.x = 10

๐Ÿ”น 3️⃣ Defining __getattr__
def __getattr__(self, name):
    return 99

This method is called only when an attribute is NOT found normally.

Parameters:

self → the object

name → name of the missing attribute

Behavior here:

If an attribute does not exist, return 99.

Example:

a.unknown → 99

๐Ÿ”น 4️⃣ Creating an Object
a = A()

Creates an instance a of class A.

Internally:

a.__dict__ = {}

The object has no instance attributes yet.

๐Ÿ”น 5️⃣ Printing Two Attributes
print(a.x, a.y)

Python evaluates both attributes separately.

๐Ÿ”น Step 1: Accessing a.x

Python follows attribute lookup order:

1️⃣ Check instance dictionary

a.__dict__

No x found.

2️⃣ Check class attributes

A.x

Found:

10

So Python returns 10.

๐Ÿ“Œ __getattr__ is NOT called because the attribute exists.

๐Ÿ”น Step 2: Accessing a.y

Now Python looks for y.

1️⃣ Instance dictionary
❌ Not found

2️⃣ Class dictionary
❌ Not found

3️⃣ Parent classes (MRO)
❌ Not found

Now Python calls:

__getattr__(self, "y")

Inside the method:

return 99

So the result is 99.

✅ Final Output
10 99

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (221) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (5) Data Analysis (27) Data Analytics (20) data management (15) Data Science (323) Data Strucures (16) Deep Learning (134) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (66) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (263) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) Python (1265) Python Coding Challenge (1080) Python Mistakes (50) Python Quiz (447) 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)