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

Wednesday, 3 December 2025

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

 


Code Explanation:

1. Class Definition
class Data:

You define a class named Data.
A class is a blueprint for creating objects that can hold data and behavior.

2. Constructor (__init__)
    def __init__(self, v):
        self.v = v

__init__ is the constructor that runs when a new Data object is created.

It accepts a parameter v and assigns it to the instance attribute self.v.

After this, every Data instance stores its value in v.

3. __repr__ Magic Method
    def __repr__(self):
        return f"<<{self.v}>>"

__repr__ is a special (magic) method that returns the “official” string representation of the object.

When you inspect the object in the REPL or use print() (if __str__ is not defined), Python will use __repr__.

This implementation returns a formatted string <<value>>, inserting the instance’s v value into the template.

4. Creating an Instance
d = Data(8)

This creates an instance d of class Data with v = 8.

The constructor stores 8 in d.v.

5. Printing the Object
print(d)

print(d) tries to convert d to a string. Because Data defines __repr__ (and no __str__), Python uses __repr__.

The __repr__ method returns the string "<<8>>", which print outputs.

Final Output
<<8>>

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

 


Code Explanation:

1. Class Definition
class Box:

Defines a new class named Box — a blueprint for creating Box objects that will hold a value n and expose a computed property.

2. Constructor
    def __init__(self, n):
        self._n = n

__init__ is the constructor; it runs when you create a Box instance.

The parameter n is passed in when constructing the object.

self._n = n stores n in the instance attribute _n. By convention the single underscore (_n) signals a “protected” attribute (meant for internal use), but it is still accessible from outside.

3. Property Definition
    @property
    def triple(self):
        return self._n * 3

@property turns the triple() method into a read-only attribute called triple.

When you access b.triple, Python calls this method behind the scenes.

return self._n * 3 computes and returns three times the stored value _n. This does not change _n — it only computes a value based on it.

4. Creating an Instance
b = Box(6)

Creates a Box object named b, passing 6 to the constructor.

Inside __init__, self._n is set to 6.

5. Accessing the Property and Printing
print(b.triple)

Accessing b.triple invokes the triple property method, which computes 6 * 3 = 18.

print outputs the returned value.

Final Output
18

Tuesday, 2 December 2025

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

 


Code Explanation:

1. Class Definition

class Hidden:

A new class named Hidden is created.

This class contains a private attribute.

2. Constructor of Hidden

    def __init__(self):

        self.__secret = 9

__init__ is the constructor.

self.__secret creates a private variable because of the double underscore __secret.

Python mangles its name internally to _Hidden__secret.

3. Child Class Definition

class Reveal(Hidden):

Reveal is a subclass of Hidden.

It inherits methods and attributes from Hidden, including the private one (internally renamed).

4. Method in Reveal

    def test(self):

        return hasattr(self, "__secret")

hasattr(self, "__secret") checks if the object has an attribute named "__secret".

BUT private attributes are name-mangled, so the real attribute name is:

_Hidden__secret

Therefore, "__secret" does not exist under that name.

So the result of hasattr(...) will be False.

5. Creating Object and Printing

print(Reveal().test())

A new Reveal object is created.

.test() is called → returns False.

False is printed on the screen.

Final Output

False


400 Days Python Coding Challenges with Explanation

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

 


Code Explanation:

1. Class Definition: class X
class X:

Defines a new class named X.

This class will act as a base/parent class.

2. Method in Class X
def val(self):
    return 3

Creates a method called val.

When called, it simply returns 3.

No parameters except self.

3. Class Definition: class Y(X)
class Y(X):

Defines class Y.

Y(X) means Y inherits from X.

So Y can access methods from X.

4. Overriding Method in Class Y
def val(self):
    return super().val() * 2

Y overrides the val() method from X.

super().val() calls the parent class (X) version of the method.

Parent method returns 3.

Then Y multiplies it by 2 → 3 * 2 = 6.

5. Creating Object of Class Y
y = Y()

Creates an object y of class Y.

6. Printing the Result
print(y.val())

Calls Y’s overridden val() method.

Computation: super().val() * 2 → 3 * 2 = 6

Output: 6

Final Output
6

Monday, 1 December 2025

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

 


Code Explanation:

1. Class Definition
class Box:

You define a class named Box, which will represent an object containing a number.

2. Constructor Method
    def __init__(self, n):
        self._n = n

Explanation:

__init__ is the constructor that runs when a new object of Box is created.

It receives the parameter n.

self._n = n stores the value in an attribute named _n.

The single underscore (_n) indicates it is a protected variable (a naming convention).

3. Property Decorator
    @property
    def double(self):
        return self._n * 2

Explanation:

@property turns the method double() into a read-only attribute.

When you access b.double, Python will automatically call this method.

It returns double of the stored number (_n * 2).

4. Creating an Object
b = Box(7)

Explanation:

Creates a new object b of class Box.

Calls __init__(7), so _n becomes 7.

5. Accessing the Property
print(b.double)

Explanation:

Accesses the property double.

Calls the method internally and returns 7 * 2 = 14.

The output printed is:

Output
14

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

 


Code Explanation:

1. Class Definition
class Alpha:

A new class Alpha is created.
This class will support custom addition using __add__.

2. Constructor Method
def __init__(self, a):
    self.__a = a

__init__ runs whenever an object is created.

self.__a is a private variable because it starts with __.

3. Overloading the + Operator
def __add__(self, other):
    return Alpha(self.__a - other.__a)

This method defines what happens when we write object1 + object2.

Instead of adding, this code subtracts the internal values.

It returns a new Alpha object with the computed value.

4. Creating Objects
x = Alpha(10)
y = Alpha(4)

x stores a private value __a = 10.

y stores a private value __a = 4.

5. Using the Overloaded + Operator
z = x + y

Calls Alpha.__add__(x, y)

Computes 10 - 4 = 6

Stores result inside a new Alpha object, assigned to z.

6. Printing the Type
print(type(z))

z is an object created by Alpha(...)

So output is:

Output
<class '__main__.Alpha'>

Sunday, 30 November 2025

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

 


Code Explanation:

1. Class Definition
class Item:

A class named Item is created.

It will represent an object that stores a price.

2. Initializer Method
    def __init__(self, p):
        self._p = p

Explanation:

__init__ is the constructor of the class.

It takes one argument p (the price).

The value is stored in a protected attribute _p.

_p means: "this is intended for internal use, but still accessible."

3. Property Decorator
    @property
    def price(self):
        return self._p + 10

Explanation:

@property turns the method price() into a read-only attribute.

Calling i.price will actually execute this method.

It returns self._p + 10, meaning:

The actual price returned is 10 more than the stored _p value.

4. Creating an Object
i = Item(50)

Explanation:
An instance of Item is created with _p = 50.

5. Accessing the Property
print(i.price)

Explanation:

Calls the price property.

Internally runs: return self._p + 10

_p = 50, so result = 60

Output
60

600 Days Python Coding Challenges with Explanation


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

 


Code Explanation:

1. Class Definition

class P:
Defines a class P, which will contain an initializer and a private variable.

2. Constructor of Class P

def __init__(self):
Defines the constructor that runs when a P object is created.

self.__v = 11
Creates a private attribute named __v and sets it to 11.
Because it starts with double underscore, Python name-mangles it to _P__v.

3. Child Class Definition

class Q(P):
Defines class Q that inherits from class P.
So Q objects automatically get all attributes and methods of P.

4. Method in Class Q

def check(self):
Defines a method inside class Q.

return hasattr(self, "__v")
The hasattr function checks whether the object has an attribute named "__v".

But due to name mangling, the actual attribute name in the object is _P__v,
NOT __v.
So this check returns False.

5. Creating an Object

q = Q()
Creates an instance of class Q.
Since Q inherits from P, the constructor of P runs → _P__v is created.

6. Printing the Result

print(q.check())
Calls check(), which checks if the object has an attribute named "__v".

It doesn’t (because it's stored as _P__v).
So it prints:
False

Output:
False

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

 


Code Explanation:

1. class Num:

Defines a class named Num that will hold a numeric value and support operator overloading.

2. def __init__(self, x):

Constructor of the class. It runs when a new Num object is created.

3. self.x = x

Stores the passed value x inside the object.

4. def __truediv__(self, other):

This method overloads the division operator / for objects of class Num.

Instead of performing division, we define a custom operation.

5. return Num(self.x + other.x)

When two Num objects are divided using /,
it returns a new Num object whose value is:

self.x + other.x

6. n1 = Num(8)

Creates a Num object with value 8.

7. n2 = Num(2)

Creates another Num object with value 2.

8. print((n1 / n2).x)

Calls the overloaded / operator
→ executes __truediv__(n1, n2)

Computes: 8 + 2 = 10

Returns Num(10)

Prints its x value → 10

Final Output
10

700 Days Python Coding Challenges with Explanation

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


Code Explanation:

1. Class Definition

class Num:
This line defines a new class named Num, which will hold a number and custom behavior for the + operator.

2. Constructor Method (__init__)

def __init__(self, n):
Defines the constructor that runs whenever a Num object is created.

self.n = n
Stores the passed value n inside the object as an attribute named n.

3. Operator Overloading (__add__)

def __add__(self, o):
Defines how the + operator works for two Num objects.
Here, self is the left operand and o is the right operand.

return Num(self.n - o.n)
Although the operator is +, this function performs subtraction.
It returns a new Num object with value self.n - o.n.

4. Creating Objects

a = Num(9)
Creates a Num object with value 9 and stores it in variable a.

b = Num(4)
Creates another Num object with value 4 and stores it in b.

5. Using the + Operator

print((a + b).n)

Python calls a.__add__(b)

Computes 9 - 4 (because __add__ subtracts)

Creates a new Num object with value 5

(a + b).n accesses the .n value of that object

print prints 5

Output:


700 Days Python Coding Challenges with Explanation

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


 Code Explanation:

1. Class definition
class Num:

Defines a class named Num. Instances of Num will hold a numeric value and support a custom subtraction behavior.

2. Constructor (__init__)
    def __init__(self, x):
        self.x = x

__init__ runs when a Num object is created.

It accepts parameter x and stores it on the instance as self.x.

3. Overloading subtraction (__sub__)
    def __sub__(self, other):
        return Num(self.x // other.x)

__sub__ is a magic method that defines what a - b does when a and b are Num objects.

Inside, it computes the floor division of the two stored values: self.x // other.x.

Floor division // divides and then rounds down to the nearest integer.

It creates and returns a new Num object initialized with that result (original objects are not modified).

4. Create first object
n1 = Num(20)


Instantiates n1 with x = 20.

5. Create second object
n2 = Num(3)


Instantiates n2 with x = 3.

6. Subtract and print the result
print((n1 - n2).x)

n1 - n2 calls Num.__sub__: computes 20 // 3 which equals 6.

__sub__ returns a new Num object with x = 6.

(n1 - n2).x accesses that new object’s x attribute.

print outputs:

6

Final output
6

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

 


Code Explanation:

1. Define base class A
class A:
    v = 5

This creates a class named A.

v is a class attribute of A with value 5.

Class attributes are shared by the class and — unless overridden — by its instances.

2. Define subclass B that inherits A
class B(A):

This creates a class B that inherits from A.

Because of inheritance, B has access to A's attributes and methods (unless overridden).

3. Override class attribute v in B
    v = 12

B defines its own class attribute v with value 12.

This shadows (overrides) the v from A for references that resolve through B or its instances (i.e., B.v or self.v inside B).

4. Define instance method show in B
    def show(self):
        return self.v + A.v

show(self) is an instance method of B.

self.v looks up v starting from the instance’s class (B) and finds B.v == 12.

A.v explicitly references the class attribute v defined on A (which is 5), bypassing the normal lookup.

The expression self.v + A.v therefore computes 12 + 5.

5. Create an instance of B
b = B()

Instantiates an object b of type B.

No __init__ defined, so default construction occurs; b can access class attributes/methods.

6. Call show() and print the result
print(b.show())

b.show() executes the show method on the b instance.

As explained, it returns 12 + 5 = 17.

print outputs:

17

Final Output
17

Thursday, 27 November 2025

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

 


Code Explanation:

1. Class Definition
class Box:

You define a new class named Box, which will hold a value and provide a computed property.

2. Constructor Method
    def __init__(self, n):
        self._n = n

__init__ is the constructor that runs when an object is created.

It takes one argument n.

The value is stored in a protected attribute _n.

3. Property Decorator
    @property
    def value(self):
        return self._n * 2

Explanation:

@property converts the method value() into an attribute-like getter.

Accessing b.value now calls this method automatically.

It returns twice the stored number (_n * 2).

4. Creating an Object
b = Box(5)

Creates an instance of Box with _n = 5.

5. Printing the Property
print(b.value)

Accesses the property value.

Internally calls value() method.

It returns 5 * 2 = 10.

Final Output
10

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

 


Code Explanation:

1. Class Definition
class Counter:

A class named Counter is created.

It will contain a class variable and a class method.

2. Class Variable
    count = 1

count is a class variable, meaning it is shared by all objects of the class.

Initially set to 1.

3. Class Method Definition
    @classmethod
    def inc(cls):
        cls.count += 2

@classmethod

The decorator @classmethod defines a method that works on the class itself, not on an instance.

inc(cls)

cls refers to the class (not an object).

Inside the method, it modifies the class variable:

cls.count += 2

Every time inc() is called, it increases count by 2.

4. Calling the Class Method – First Call
Counter.inc()

Calls the class method directly using the class name.

count increases from 1 → 3.

5. Calling the Class Method – Second Call
Counter.inc()

Called again.

count increases from 3 → 5.

6. Printing the Final Count
print(Counter.count)

Prints the final value of the class variable count.

Output:

5

Final Output
5

Wednesday, 26 November 2025

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

 


Code Explanation:

1. Class Definition
class Num:

This defines a new class called Num.

Each object represents a number stored in the attribute x.

The class includes operator overloading for *.

2. Constructor Method
    def __init__(self, x):
        self.x = x

__init__ is the constructor method in Python.

It is called automatically when a new object is created.

x is passed as a parameter and stored as an instance attribute self.x.

3. Operator Overloading (*)
    def __mul__(self, other):
        return Num(self.x + other.x)

__mul__ is a magic method that defines how the * operator works for Num objects.

self refers to the current object, and other refers to the second object in the operation.

Instead of normal multiplication, this method adds the x values of both objects.

It returns a new Num object with x = self.x + other.x.

4. Creating Object n1
n1 = Num(7)

Creates a Num object n1 with x = 7.

The constructor __init__ is called automatically.

5. Creating Object n2
n2 = Num(9)

Creates another Num object n2 with x = 9.

6. Using * Operator
print((n1 * n2).x)

n1 * n2 calls the __mul__ method.

Inside __mul__, it calculates n1.x + n2.x = 7 + 9 = 16.

Returns a new Num object with x = 16.

(n1 * n2).x accesses the x attribute of the new object.

Output:

16



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

 


Code Explanation:

1. Class Definition
class Num:

This defines a new class called Num.

Each object of this class represents a number stored in the attribute x.

The class will also define how objects behave when used with operators like +.

2. Constructor Method
    def __init__(self, x):
        self.x = x

__init__ is the constructor method, called automatically when a new object is created.

x is a parameter passed during object creation.

self.x = x stores the value of x inside the object as an instance attribute.

3. Operator Overloading (+)
    def __add__(self, other):
        return Num(self.x * other.x)

__add__ is a magic method that defines the behavior of the + operator.

self is the current object, other is another object of the same class.

Instead of normal addition, this method multiplies the x values of the two objects and returns a new Num object.

4. Creating Object n1
n1 = Num(3)

This creates a Num object n1 with x = 3.

The constructor __init__ is called automatically.

5. Creating Object n2
n2 = Num(4)

This creates a second Num object n2 with x = 4.

6. Using + Operator
print((n1 + n2).x)

n1 + n2 calls the __add__ method.

Inside __add__, it multiplies n1.x * n2.x = 3 * 4 = 12.

Returns a new Num object with x = 12.

(n1 + n2).x accesses the x attribute of the new object.

print outputs:

12

Summary

Num objects can use +, but it multiplies values instead of adding.

__add__ returns a new object, leaving original objects unchanged.

Output :

12

Tuesday, 25 November 2025

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

 

Code Explanation:

1. Class Definition
class Data:

This creates a new class named Data.

Objects created from this class will hold a data value and know how to represent themselves as text.

2. Constructor Method
    def __init__(self, d):
        self.d = d

__init__ runs every time a new object is created.

It receives a value d and stores it in the object as self.d.

So each Data object will have a d attribute.

3. Magic Method __repr__
    def __repr__(self):
        return f"Data={self.d}"

__repr__ is a magic method that defines how an object should be represented as a string, mainly for debugging.

When you print an object, Python prefers __str__, but if it is not defined, Python uses __repr__.

It returns a string like "Data=9" when the object's d is 9.

4. Creating an Object
obj = Data(9)

Creates an instance named obj with d = 9.

The constructor stores 9 inside self.d.

5. Printing the Object
print(obj)

Since no __str__ method exists, Python uses __repr__.

__repr__ returns:

Data=9


This becomes the final print output.

Final Output
Data=9

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


 

Code Explanation:

1. Class Definition Begins
class X:

A new class X is created.

This class contains one method, get().

2. Method Inside Class X
    def get(self):
        return 2

The method get() always returns the integer 2.

Any object of class X will return 2 when get() is called.

3. Class Y Inheriting From X
class Y(X):

Class Y is created, and it inherits from class X.

This means Y has access to all methods defined in X unless overridden.

4. Overriding the get() Method in Class Y
    def get(self):
        return super().get() + 3

Class Y provides its own version of the get() method.

super().get() calls the parent class (X) version of get(), which returns 2.

Then 3 is added to the result.

Final returned value = 2 + 3 = 5.

5. Creating Object of Class Y
y = Y()

An object y is created from class Y.

This object has access to Y’s overridden get() method.

6. Printing the Result
print(y.get())

Calls Y’s get() method.

That method calls X’s get() → returns 2.

Adds 3 → result = 5.

Prints:

5

Final Output
5

100 Python Programs for Beginner with explanation

Monday, 24 November 2025

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

 


Code Explanation:

1. Class Definition
class Test:

A class named Test is created.

Objects of this class will use the special methods __repr__ and __str__.

2. Defining __repr__ Method
    def __repr__(self):
        return "REPR"

__repr__ is a magic method that returns the official, developer-friendly string representation of an object.

It is used in debugging, lists of objects, the Python shell, etc.

This method returns the string "REPR".

3. Defining __str__ Method
    def __str__(self):
        return "STR"

__str__ is another magic method that defines the user-friendly string representation.

It is used when you call print(object) or str(object).

It returns the string "STR".

4. Creating an Object
t = Test()

An object t of class Test is created.

Now t has access to both __repr__ and __str__.

5. Printing the Object
print(t)

When printing an object, Python always calls __str__ first.

Since the class defines a __str__ method, Python uses it.

Therefore the printed output is:

STR

Final Output
STR

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

 

Code Explanation:

1. Class P definition
class P:

Declares a new class named P.

P will act as a base (parent) class for other classes.

2. __init__ constructor in P
    def __init__(self):
        self.__v = 12

Defines the constructor that runs when a P (or subclass) instance is created.

self.__v = 12 creates an attribute named __v on the instance.

Because the name starts with two underscores, Python will name-mangle this attribute to _P__v internally to make it harder to access from outside the class (a form of limited privacy).

3. Class Q definition inheriting from P
class Q(P):

Declares class Q that inherits from P.

Q gets P’s behavior (including __init__) unless overridden.

4. check method in Q
    def check(self):
        return hasattr(self, "__v")

Defines a method check() on Q that tests whether the instance has an attribute literally named "__v" (not the mangled name).

hasattr(self, "__v") looks for an attribute with the exact name __v on the instance — it does not account for name mangling.

5. Create an instance of Q
q = Q()

Instantiates Q. Because Q inherits P, P.__init__ runs and sets the instance attribute — but under the mangled name _P__v, not __v.

6. Print the result of q.check()
print(q.check())

Calls check() which runs hasattr(self, "__v").

The instance does not have an attribute literally named __v (it has _P__v), so hasattr returns False.

The printed output is:

False

Final Output:

False

Popular Posts

Categories

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

Followers

Python Coding for Kids ( Free Demo for Everyone)