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

Thursday, 11 December 2025

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

 


Code Explanation: 

1. Class Definition
class Test:

Explanation:

A class named Test is created.

It contains a method show() that behaves differently depending on how many arguments are passed.

This is an example of method overloading-like behavior in Python.

2. Method Definition With Default Parameters
def show(self, a=None, b=None):

Explanation:

The method show() takes two optional parameters: a and b.

a=None and b=None mean that unless values are given, they automatically become None.

3. First Condition
if a and b:
    return a + b

Explanation:

This runs when both a and b have truthy (non-zero/non-None) values.

It returns a + b.

4. Second Condition
elif a:
    return a

Explanation:

This runs when only a is truthy.

It returns just a.

5. Default Return
return "No Value"

Explanation:

If neither a nor b are given, the method returns the string "No Value".

6. First Function Call
Test().show(5)

Explanation:

Here, a = 5, b = None

Condition check:

if a and b → False (b is None)

elif a → True

So it returns 5.

7. Second Function Call
Test().show(5, 10)

Explanation:

Here, a = 5, b = 10

Condition check:

if a and b → True

So it returns 5 + 10 = 15.

8. Final Print Statement
print(Test().show(5), Test().show(5, 10))

Explanation:

First call prints 5

Second call prints 15

Final Output
5 15

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

 

Code Explanation:

1. Class Definition
class Player:
    score = 5

Explanation:

A class named Player is created.

score = 5 is a class variable.

Class variables belong to the class itself, not to individual objects.

All objects will share the same class variable unless overridden by instance variable.

2. Creating First Object
p1 = Player()
Explanation:

An object p1 of class Player is created.

p1 does not have its own score, so it will use the class variable score = 5.

3. Changing Class Variable Directly Using Class Name
Player.score = 20
Explanation:

This line updates the class variable.

Now the class variable score becomes 20.

Every object that does not have its own score variable will see 20.

4. Creating Second Object
p2 = Player()

Explanation:

Another object p2 is created.

Since class variable score was updated to 20,
p2.score will be 20.

5. Print Values
print(p1.score, p2.score)

Explanation:

p1.score
p1 does not have its own score
uses class variable → 20

p2.score
same logic → 20

Final Output
20 20

Wednesday, 10 December 2025

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

 


Code Explanation:

1. Class Definition
class A:

Explanation:

Defines a class named A.

2. Class Variable
x = 10

Explanation:

This is a class variable.

It belongs to the class, not to any specific object.

It can be accessed using:

A.x

obj.x

3. Method Definition
def show(self):

Explanation:

show is an instance method.

self refers to the current object.

x = 20

Explanation:

This creates a local variable x inside the show() method.

This does NOT change:

the class variable x

or the object variable

This x = 20 exists only inside this method.

4. Object Creation
obj = A()
Explanation:

Creates an object obj of class A.

No instance variable x is created here.

The class variable x = 10 still exists.

5. Method Call
obj.show()

Explanation:

Calls the show() method.

Inside show():

x = 20 is created as a local variable

It is destroyed after the method finishes

It does NOT affect obj.x or A.x.

6. Print Statement
print(obj.x)

Explanation:

Since obj has no instance variable x, Python looks for:

Instance variable 

Class variable 

It finds:

A.x = 10


So it prints 10.

Final Output
10

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


 Code Explanation:

1. Class Definition
class Test:

Explanation:

This line defines a class named Test.

A class is a blueprint used to create objects.

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

__init__ is a special constructor method.

It is called automatically when a new object is created.

self refers to the current object.

x is a parameter passed while creating the object.

self.x = x

Explanation:

This line stores the value of x inside the object.

It creates an instance variable named x.

3. Operator Overloading Method (__add__)
def __add__(self, other):
Explanation:

__add__ is a special method used for operator overloading.

It allows us to use the + operator with class objects.

self → first object

other → second object

return self.x + other.x

Explanation:

This adds:

self.x → value from first object

other.x → value from second object

It returns the sum of the two values.

4. Object Creation
obj1 = Test(5)

Explanation:

Creates an object obj1.

Calls the constructor: self.x = 5

So, obj1.x = 5

obj2 = Test(10)

Explanation:

Creates another object obj2.

Calls the constructor: self.x = 10

So, obj2.x = 10

5. Addition Operation
print(obj1 + obj2)
Explanation:

obj1 + obj2 automatically calls:

obj1.__add__(obj2)

Which returns:

5 + 10 = 15

Final Output
15

Tuesday, 9 December 2025

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

 


Code Explanation:

1. Defining the Class
class Box:

This line defines a class named Box.
A class acts as a template for creating objects.

2. Creating the Constructor Method
def __init__(self, n):

This is the constructor method.
It runs automatically when a new object is created.
self → Refers to the current object
n → A value passed while creating the object

3. Initializing an Instance Variable
self.n = n

This creates an instance variable n.
The value passed during object creation is stored in self.n.

After this:

self.n → 5

4. Defining the __repr__ Method
def __repr__(self):

__repr__ is a special method in Python.
It defines how an object should be displayed when printed.

5. Returning a Formatted String
return f"Box({self.n})"

This returns a formatted string representation of the object.
self.n is inserted into the string using an f-string.

This means:

repr(b) → "Box(5)"

6. Creating an Object
b = Box(5)

This creates an object b of the class Box.
The value 5 is passed to the constructor and stored in b.n.

7. Printing the Object
print(b)

When print(b) is executed, Python automatically calls:

b.__repr__()

Which returns:

"Box(5)"
So the final output is:

Box(5)

Final Output
Box(5)

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

 


Code Explanation:

1. Defining a Class
class User:

This line defines a class named User.
A class is like a blueprint for creating objects.

2. Creating the Constructor Method
def __init__(self, name):

This is a constructor method.
It runs automatically when a new object is created from the class.

self → Refers to the current object.
 name → A parameter used to pass the user's name.

3. Initializing an Attribute
self.name = name

This line creates an instance variable called name.
It stores the value passed during object creation.

4. Creating an Object of the Class
u = User("Sam")

This creates an object u of the User class.
"Sam" is passed to the constructor and stored in u.name.

Now:

u.name → "Sam"

5. Adding a New Attribute Dynamically
u.score = 90

This adds a new attribute score to the object u.
Python allows adding new attributes to objects outside the class.

Now:

u.score → 90

6. Printing the Attribute Value
print(u.score)
This prints the value of the score attribute.
Output will be:
90

Final Output
90

Monday, 8 December 2025

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

 


Code Explanation:

1. Class Definition
class Num:

This defines a class named Num.

It is a blueprint for creating objects that store a number.

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

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

x is the value passed while creating the object.

self.x = x stores the value inside the object.

3. Operator Overloading for /
    def __truediv__(self, other):
        return Num(self.x * other.x)

__truediv__ is a magic method that overloads the / operator.

Instead of performing division, this method performs multiplication.

self.x * other.x multiplies the values.

A new Num object is returned with the multiplied value.

4. Creating First Object
n1 = Num(2)

Creates an object n1.

self.x = 2 is stored in n1.

5. Creating Second Object
n2 = Num(6)

Creates another object n2.

self.x = 6 is stored in n2.

6. Using the / Operator
print((n1 / n2).x)

n1 / n2 calls the __truediv__ method.

Inside the method:

self.x * other.x = 2 * 6 = 12

A new Num(12) object is created.

.x extracts the value 12.

print() displays:

12

Final Output
12

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

 


Code Explanation:

1. Defining the Class
class Data:

This creates a new class named Data.

A class is a blueprint for creating objects (instances) that can hold data and behavior.

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

__init__ is the constructor method. It runs automatically when you create a new Data object.

Parameter v is the value passed while creating the object.

self.v = v stores that value in an instance attribute named v.

So each Data object will have its own v.

3. Defining __repr__ (Representation Method)
    def __repr__(self):
        return f"Value={self.v}"

__repr__ is a magic (dunder) method that defines how the object is represented as a string, mainly for debugging or interactive console.

When you do print(d) or just type d in a Python shell, Python calls __repr__ (if __str__ isn’t defined).

It returns a formatted string:

f"Value={self.v}" → uses f-string to embed the value of self.v.

For example, if self.v = 9, it returns "Value=9".

4. Creating an Object
d = Data(9)

This creates an instance d of the Data class.

__init__ is called with v = 9.

Inside __init__, self.v is set to 9.

So now d.v == 9.

5. Printing the Object
print(d)

When you pass d to print(), Python looks for:

First: __str__ method (not defined here)

Then: __repr__ method (defined!)

So it calls d.__repr__(), which returns "Value=9".

print outputs:

Value=9

Final Output
Value=9

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

 


Code Explanation:

Class Definition
class Product:

This defines a new class named Product.

The class will represent a product that has a price and some logic around it.

Constructor (__init__) Method
    def __init__(self, p):
        self._price = p

__init__ is the constructor — it runs automatically when you create a new Product object.

It takes one argument besides self: p, which represents the base price.

self._price = p:

Stores the value of p in an attribute called _price.

The single underscore _price is a convention meaning “internal use” (protected-style attribute).

Property Decorator
    @property
    def price(self):
        return self._price * 2

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

That means you can access price like p.price instead of p.price().

Inside the method:

return self._price * 2

It doesn’t return the raw _price.

Instead, it returns double the stored price.

This is a form of encapsulation + computed property:
the internal value is _price, but the external visible value is _price * 2.

Creating an Object
p = Product(40)

Creates an instance p of the Product class.

Calls __init__(self, p) with p = 40.

Inside __init__, _price becomes 40.
So now: p._price == 40.

Accessing the Property
print(p.price)

Accessing p.price triggers the @property method price().

It calculates: self._price * 2 → 40 * 2 = 80.

print outputs:

80

Final Output
80

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

 


Code Explanation:

1. Defining Class A
class A:

This line defines a new class named A.

A class is a blueprint used to create objects.

2. Defining Method in Class A
    def val(self):
        return 4

val() is an instance method of class A.

self refers to the current object.

This method simply returns the value 4.

3. Defining Class B (Inheritance)
class B(A):

This defines a new class B.

B(A) means B inherits from A.

So, class B has access to methods of class A.

4. Overriding Method in Class B
    def val(self):

Class B overrides the val() method of class A.

This means B provides its own version of the method.

5. Calling Parent Method Using super()
        return super().val() + 6

super().val() calls the parent class (A) method val().

A.val() returns 4.

Then + 6 is added:

4 + 6 = 10

So this method returns 10.

6. Creating Object and Printing Output
print(B().val())

B() creates an object of class B.

.val() calls the overridden method in class B.

The method returns 10.

print() displays:

10

Final Output
10


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

 


Code Explanation:

1. Class Definition
class A:

This defines a class named A.

A class is a blueprint for creating objects.

Any object created from this class will follow its structure.

2. Constructor Method
    def __init__(self):

__init__ is the constructor.

It runs automatically when an object is created.

It is used to initialize object data.

3. Private Variable Creation
        self.__x = 5

__x is a private variable.

Python performs name mangling, converting:

__x → _A__x


This prevents direct access from outside the class.

The value 5 is safely stored inside the object.

4. Object Creation
a = A()

An object named a is created.

The constructor runs automatically.

Now internally the object contains:

a._A__x = 5

5. Checking Attribute Using hasattr()
print(hasattr(a, "__x"))

hasattr(object, "attribute") checks if the attribute exists.

Since __x was name-mangled to _A__x,
the exact name "__x" does not exist in the object.

So this returns:

False

Final Output
False

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

 


Code Explanation:1. Class Definition

class Info:

This line defines a new class named Info.

A class is a blueprint for creating objects.

Objects created from this class will store a value and display it in a custom format.

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

__init__ is the constructor method.

It runs automatically when a new object is created.

n is the value passed while creating the object.

self.n = n stores that value inside the object as an instance variable.

3. __repr__ Magic Method
    def __repr__(self):
        return f"Info[{self.n}]"

__repr__ is a special (magic) method used to define how the object looks when printed.

It returns a formatted string showing the value of n.

So if n = 11, it will return:

Info[11]

4. Object Creation
i = Info(11)

This creates an object i of the Info class.

The constructor assigns:

i.n = 11

5. Printing the Object
print(i)

print(i) automatically calls the __repr__ method.

It prints the formatted string returned by __repr__.

Final Output
Info[11]

Saturday, 6 December 2025

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

 


Code Explanation:

Defining Class A
class A:

This creates a class named A.

It will act as a base (parent) class.

Method Inside Class A
    def get(self):
        return "A"

Defines a method get inside class A.

When get() is called on an object of class A, it will return the string "A".

Defining Class B That Inherits from A
class B(A):

Creates a new class B that inherits from A.

That means B automatically gets all methods and attributes of A (unless overridden).

Overriding get in Class B
    def get(self):
        return "B"

Class B defines its own version of the get method.

This overrides the get method from class A.

Now, when get() is called on a B object, it returns "B" instead of "A".

Defining Class C That Inherits from B
class C(B):
    pass

Class C is defined and it inherits from B.

The pass statement means no new methods or attributes are added in C.

So C simply uses whatever it gets from B (and indirectly from A).

Creating an Object of C and Calling get
print(C().get())

C() creates a new object of class C.

.get() calls the get method on that object.

Python looks for get method in this order (MRO):

First in C → none

Then in B → found def get(self): return "B"

So it uses B’s version of get, which returns "B".

Final printed output:

B

Final Answer:

B

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

 


Code Explanation:

1. Defining the Class
class User:

This defines a new class called User.

A class is a blueprint for creating objects (instances).

Objects of User will represent users with some attributes (like name, age, etc.).

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

__init__ is the constructor method.

It runs automatically when you create a new User object.

It takes one parameter besides self: name.

self.name = name creates an instance attribute name and assigns it the value passed when creating the object.

After this, every User object will have its own name.

3. Creating an Object of User
u = User("Tom")

This line creates an object u of class User.

It calls the constructor: __init__(u, "Tom").

Inside __init__, self.name becomes "Tom".

So now:

u.name == "Tom"

4. Adding a New Attribute Dynamically
u.age = 18

Here, you are adding a new attribute age to the object u outside the class definition.

Python allows dynamic attributes, so you don’t need to declare all attributes inside __init__.

Now u has:

u.name = "Tom"

u.age = 18

5. Printing the age Attribute
print(u.age)

This accesses the age attribute of object u.

Since you set u.age = 18 earlier, this prints:

18

Final Output
18

Thursday, 4 December 2025

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

 


Code Explanation:

1. Class Definition
class Item:

This defines a new class called Item.

Classes are blueprints for objects, which can have attributes and methods.

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

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

p is passed as a parameter when creating the object.

self._price = p stores the price in a protected attribute _price.

By convention, a single underscore _ indicates that this attribute should not be accessed directly outside the class.

3. Property Decorator
    @property
    def price(self):
        return self._price + 20

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

When you access i.price, it automatically calls this method.

The method returns _price plus 20, effectively adding a fixed markup to the price.

Benefit: You can compute or validate values dynamically while keeping a clean attribute-like access.

4. Creating an Object
i = Item(80)

Creates an object i of the class Item with _price = 80.

The constructor initializes the protected attribute _price.

5. Accessing the Property
print(i.price)

Accessing i.price calls the price property method.

The method calculates _price + 20 = 80 + 20 = 100.

print outputs:

100

Final Output:
100

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


 Code Explanation:

1. Class Definition
class Counter:

This defines a new class named Counter.

A class is a blueprint for creating objects, and can contain class variables, instance variables, and methods.

2. Class Variable
    count = 0

count is a class variable, shared among all instances of the class.

Every object of Counter accesses the same count.

Initially, count is set to 0.

3. Class Method Definition
    @classmethod
    def increment(cls):

@classmethod decorator defines a class method.

cls refers to the class itself (not an instance).

Class methods can access and modify class variables.

4. Modifying the Class Variable
        cls.count += 3

Inside the class method, cls.count accesses the shared class variable count.

It increments count by 3 each time the method is called.

Changes affect all objects of the class because count is shared.

5. Calling Class Method
Counter.increment()
Counter.increment()
The class method increment is called twice using the class name.

First call: count = 0 + 3 = 3

Second call: count = 3 + 3 = 6

6. Printing the Class Variable
print(Counter.count)

Accessing Counter.count prints the current value of the class variable count.

Output:

6

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

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (225) Data Strucures (14) Deep Learning (75) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (48) 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 (197) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1219) Python Coding Challenge (898) Python Quiz (348) 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)