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

Sunday, 16 November 2025

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

 


Code Explanation:

1. Class Definition Begins
class Demo:

A new class named Demo is created.
This class will contain attributes and methods.

2. Class-Level Attribute
    nums = []

nums is a class variable (shared by all objects of the class).

It is an empty list [] initially.

Any object of Demo will use this same list unless overridden.

3. Method Definition
    def add(self, val):
        self.nums.append(val)

The method add() takes self (object) and a value val.

It appends val to self.nums.

Since nums is a class list, appending through any object affects the same list.

4. Creating First Object
d1 = Demo()

Creates object d1 of class Demo.

d1 does not have its own nums; it uses the shared class list.

5. Creating Second Object
d2 = Demo()

Creates another object d2.

d2 also uses the same class-level list nums as d1.

6. Adding a Number Using d1
d1.add(4)

Calls the add() method on d1.

This executes self.nums.append(4).

Since nums is shared, the list becomes:
[4]

7. Printing Length of nums from d2
print(len(d2.nums))

d2 looks at the same shared list.

That list contains one element: 4

So length is:

1

Final Output:
1

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

 


Code Explanation:

1. Class Definition Begins
class A:

You define a class A.
This is a blueprint for creating objects.

2. Method Inside Class A
    def show(self):
        return "A"

A method named show() is created.

When this method is called, it returns the string "A".

3. Class B Inherits Class A
class B(A):

Class B is created.

It inherits from class A, meaning B gets all attributes/methods of A unless overridden.

4. Overriding the show() Method in Class B
    def show(self):
        return super().show() + "B"

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

super().show() calls the show() method from the parent class A, which returns "A".

Then "B" is added.

So the full returned string becomes: "A" + "B" = "AB".

5. Creating an Object of Class B
obj = B()

An object named obj is created using class B.

This object can use all methods of B, and inherited methods from A.

6. Calling the show() Method
print(obj.show())

Calls B’s version of show().

That method calls super().show() → returns "A"

Adds "B" → becomes "AB"

Finally prints:

AB

Final Output: AB

500 Days Python Coding Challenges with Explanation

Friday, 14 November 2025

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

 


Code Explanation:

1. Defining the Class
class Calc:

Creates a class named Calc.

A class acts as a blueprint to define objects and their behavior (methods).

2. Defining a Method
def add_even(self, n):
    return n if n % 2 == 0 else 0

Defines a method called add_even that takes one number n.

self refers to the object that will call this method.

The method uses a ternary operator:

If n is even → returns n

If n is odd → returns 0

3. Creating an Object
c = Calc()

Creates an object c of the Calc class.

This object can now call the add_even() method.

4. Initializing the Sum
s = 0

Initializes a variable s to 0.

This will store the sum of even numbers.

5. Looping from 1 to 5
for i in range(1, 6):
    s += c.add_even(i)

range(1, 6) generates numbers 1, 2, 3, 4, 5.

For each i, the method add_even(i) is called.

Only even numbers are added to s.

Step-by-step trace:

i c.add_even(i) s after addition
1 0 0
2 2 2
3 0 2
4 4 6
5 0 6

6. Printing the Result
print(s)

Prints the final accumulated sum of even numbers from 1 to 5.

Final Output
6



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

 


Code Explanation:

1. Defining the Class

class A:

Creates a class named A.

A class acts as a blueprint for creating objects (instances).

2. Declaring a Class Variable

count = 0

count is a class variable, shared across all instances of class A.

Initially, A.count = 0.

3. Defining the Constructor

def __init__(self):

    A.count += 1

__init__ is the constructor, executed automatically when an object is created.

Each time a new object is created, A.count increases by 1.

This tracks how many objects have been created.

4. Loop to Create Objects

for i in range(3):

    a = A()

The loop runs 3 times (i = 0, 1, 2).

Each iteration creates a new object of class A, calling the constructor.

After each iteration, A.count increases:

Iteration Action A.count

1 new A() 1

2 new A() 2

3 new A() 3

Variable a always refers to the last object created.

5. Printing the Class Variable

print(A.count)

Accesses the class variable count directly through the class A.

Since 3 objects were created, A.count = 3.

Prints 3.

Final Output

3




Thursday, 13 November 2025

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

 


Code Explanation:

1. Defining the Class
class Check:

A class named Check is created.

It will contain a method that checks if a number is even.

2. Defining the Method
def even(self, n):
    return n if n % 2 == 0 else 0

even() is an instance method that takes one argument n.

It uses a conditional expression (ternary operator):

If n % 2 == 0 → number is even → return n.

Otherwise → return 0.

In simple terms:
Even number → returns itself
Odd number → returns 0

3. Creating an Object
c = Check()

Creates an instance c of the Check class.

This object can now call the even() method.

4. Initializing a Variable
s = 0

A variable s is set to 0.

It will be used to accumulate the sum of even numbers.

5. Loop from 1 to 5
for i in range(1, 6):
    s += c.even(i)

The loop runs for i = 1, 2, 3, 4, 5.

Each time, it calls c.even(i) and adds the result to s.

Let’s trace it step-by-step:

Iteration i c.even(i) Calculation s after iteration
1 1 0 (odd) 0 + 0 0
2 2 2 (even) 0 + 2 2
3 3 0 (odd) 2 + 0 2
4 4 4 (even) 2 + 4 6
5 5 0 (odd) 6 + 0 6


6. Printing the Result
print(s)

Prints the final accumulated value of s.

After the loop, s = 6.

Final Output
6


400 Days Python Coding Challenges with Explanation

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

 


Code Explanation:

1. Defining the Class
class Word:

Creates a class named Word.

This class can contain methods to perform operations on words or strings.

2. Defining a Method
def vowels(self, word):

Defines a method named vowels inside the Word class.

self refers to the instance of the class calling the method.

word is the string parameter for which we want to count vowels.

3. Initializing a Counter
count = 0

Initializes a variable count to 0.

This variable will keep track of the number of vowels found in the word.

4. Looping Through Each Character
for ch in word:

Iterates over each character ch in the input string word.

5. Checking if Character is a Vowel
if ch.lower() in "aeiou":
    count += 1

ch.lower() converts the character to lowercase, so the check is case-insensitive.

If the character is in "aeiou" → it is a vowel → increment count by 1.

Let’s trace for "Object":

Character ch.lower() Vowel? count after step
O                   o                   Yes        1
b                   b                    No        1
j                         j                    No        1
e                   e                    Yes        2
c                   c                    No        2
t                   t                    No        2
6. Returning the Count
return count


Returns the total number of vowels found in the word.

7. Creating an Object
w = Word()

Creates an instance w of the Word class.

This object can now call the vowels() method.

8. Calling the Method and Printing
print(w.vowels("Object"))

Calls the vowels() method on the object w with "Object" as input.

Returns 2 → number of vowels (O and e).

print() displays the result.

Final Output
2

400 Days Python Coding Challenges with Explanation

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

Code Explanation:

1. Defining the Class
class Math:

This line defines a class called Math.

A class is a blueprint for creating objects.

All methods related to mathematical operations can go inside this class.

2. Defining the Method
def fact(self, n):

Defines a method called fact to calculate the factorial of a number n.

self refers to the instance of the class that will call this method.

3. Initializing the Result Variable
res = 1

Initializes a variable res to 1.

This variable will store the factorial as it is computed in the loop.

4. Loop to Compute Factorial
for i in range(1, n+1):
    res *= i

range(1, n+1) generates numbers from 1 to n inclusive.

On each iteration, res *= i multiplies the current value of res by i.

Let’s trace it for n = 4:

Iteration i res calculation res after iteration
1 1 1 * 1 1
2 2 1 * 2 2
3 3 2 * 3 6
4 4 6 * 4 24

5. Returning the Result
return res

After the loop, res holds the factorial of n.

return res sends this value back to the caller.

6. Creating an Object
m = Math()

Creates an instance m of the class Math.

This object can now access the fact method.

7. Calling the Method and Printing
print(m.fact(4))

Calls fact(4) on object m.

Computes 4! = 1*2*3*4 = 24.

print() outputs the result to the console.

Final Output
24

500 Days Python Coding Challenges with Explanation

 

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

 


Code Explanation:

1. Defining the Class
class A:

A new class named A is created.

This acts as a blueprint for creating objects (instances).

2. Declaring a Class Variable
count = 0

count is a class variable, shared by all objects of class A.

It belongs to the class itself, not to individual instances.

Initially, A.count = 0.

3. Defining the Constructor
def __init__(self):
    A.count += 1

__init__ is the constructor, called automatically every time an object of class A is created.

Each time an object is created, this line increases A.count by 1.

So it counts how many objects have been created.

4. Loop to Create Multiple Objects
for i in range(3):
    a = A()

The loop runs 3 times (i = 0, 1, 2).

Each time, a new object a of class A is created, and the constructor runs.

Let’s trace it:

Iteration Action A.count value
1st (i=0) new A() created 1
2nd (i=1) new A() created 2
3rd (i=2) new A() created 3

After the loop ends, A.count = 3.

The variable a refers to the last object created in the loop.

5. Printing the Count
print(a.count)

Here, we access count through the instance a, but since count is a class variable, Python looks it up in the class (A.count).

The value is 3.

Final Output
3

500 Days Python Coding Challenges with Explanation

Tuesday, 11 November 2025

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

 


Code Explanation:

1. Defining Class A
class A:

Creates a class named A.

This class will contain methods that objects of class A can use.

2. Defining Method in Class A
def value(self):

Declares a method called value inside class A.

self refers to the instance of the class.

3. Returning Value from Class A
return 2

When value() is called on A, it will return the integer 2.

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

Defines a class B that inherits from class A.

This means B automatically gets all methods of A unless overridden.

5. Overriding Method in Class B
def value(self):

Class B creates its own version of the method value.

This overrides the version from class A.

6. Using super() Inside B’s Method
return super().value() + 3

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

A.value() returns 2.

Then + 3 is added → result becomes 5.

7. Calling the Method
print(B().value())

B() creates an object of class B.

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

It computes 2 + 3 → 5.

print() prints 5.

Final Output
5

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

 


Code Explanation:

1. Defining Class T
class T:

Creates a class named T.

The class will contain a static method.

2. Declaring a Static Method
@staticmethod
def calc(a, b):

@staticmethod tells Python that calc does not depend on any instance (self) or class (cls).

It behaves like a normal function but lives inside the class.

You don’t need self or cls parameters.

3. Returning the Calculation
return a * b

calc simply multiplies the two arguments and returns the product.

4. Creating an Instance of Class T
t = T()

Creates an object named t of class T.

Even though calc is static, it can still be called using this instance.

5. Calling Static Method Through Instance
t.calc(2, 3)

Calls calc using the instance t.

Since it's a static method, Python does NOT pass self.

It executes 2 * 3 → 6.

6. Calling Static Method Through Class
T.calc(3, 4)

Calls the static method using the class name T.

Again, multiplies the numbers: 3 * 4 → 12.

7. Printing Both Results
print(t.calc(2, 3), T.calc(3, 4))

Prints the two results side-by-side:

First: 6

Second: 12

Final Output
6 12

Monday, 10 November 2025

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

 


Code Explanation:

Import the dataclass decorator
from dataclasses import dataclass

Imports the @dataclass decorator from Python’s dataclasses module.

@dataclass automatically generates useful methods like:

__init__() → constructor

__repr__() → string representation

Define the Product dataclass
@dataclass
class Product:

Declares a class Product as a dataclass.

Dataclasses are useful for storing data with minimal boilerplate.

Declare class fields
    price: int
    qty: int

These are the two attributes of the class:

price → the price of the product

qty → the quantity of the product

With @dataclass, Python automatically creates an __init__ method that initializes these fields.

Create objects and perform calculation
print(Product(9, 7).price * 2 + Product(9, 7).qty)

Product(9, 7) → Creates a Product object with price = 9 and qty = 7.

.price * 2 → 9 * 2 = 18

+ Product(9, 7).qty → 18 + 7 = 25

print() → Outputs 25.

Final Output
25



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


 Code Explanation:

1) Define the class
class Square:

This starts the definition of a class named Square.

It will represent a square with side length s.

2) Constructor method (__init__)
    def __init__(self, s):
        self.s = s

__init__ runs whenever a new Square object is created.

It takes s (the side length) and stores it in the instance variable self.s.

3) Create a computed property
    @property
    def diag(self):
        return (2 * (self.s**2)) ** 0.5
@property

This decorator makes diag behave like an attribute instead of a method.

So we can use Square(4).diag instead of Square(4).diag().

diag calculation

A square’s diagonal formula is:

(2 * (self.s**2)) ** 0.5

self.s**2 → square of the side

Multiply by 2 → gives 2s²

Raise to power 0.5 → square root

4) Create an object and print diagonal
print(int(Square(4).diag))

Square(4) creates a square with side = 4.

.diag fetches its diagonal value:

2×16=32 ≈5.656

int(...) converts it to an integer → 5.

print() outputs the value.

Final Output
5

Sunday, 9 November 2025

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


Code Explanation:

1) Import the dataclass decorator

from dataclasses import dataclass

This imports the dataclass decorator from Python’s dataclasses module.

@dataclass automatically creates useful methods (like __init__) for classes.


2) Define the dataclass

@dataclass

class Marks:

@dataclass tells Python to turn Marks into a dataclass.

This means it will auto-generate an initializer (__init__) taking m1 and m2.


3) Declare fields of the class

    m1: int

    m2: int

These are the attributes of the class.

m1 and m2 are typed as integers, representing two marks.


4) Define a method to compute total

    def total(self):

        return (self.m1 + self.m2) // 2

total() is an instance method.

It adds the two marks and uses // 2 which performs integer division (floor division).

This returns the average of the two marks as an integer.


5) Create an object and print result

print(Marks(80, 90).total())

Marks(80, 90) creates an object with m1 = 80, m2 = 90.

.total() computes (80 + 90) // 2 = 170 // 2 = 85.

print() displays the result.


Final Output

85

600 Days Python Coding Challenges with Explanation

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


Code Explanation:

1) Define the class
class Convert:

This starts the definition of a class named Convert.

A class groups related data (attributes) and behavior (methods).

2) Class attribute factor
    factor = 1.5

factor is a class variable (shared by the class and all its instances).

It’s set to the floating-point value 1.5.

You can access it as Convert.factor or cls.factor inside classmethods.

3) Mark the next method as a class method
    @classmethod

The @classmethod decorator makes the following method receive the class itself as the first argument (conventionally named cls) instead of an instance (self).

Class methods are used when a method needs to read/modify class state.

4) Define the apply class method
    def apply(cls, x):
        return x * cls.factor

apply takes two parameters: cls (the class object) and x (a value to process).

Inside the method, cls.factor looks up the class attribute factor.

The method returns the product of x and the class factor (i.e., x * 1.5).

5) Call the class method and convert to int
print(int(Convert.apply(12)))

Convert.apply(12) calls the class method with x = 12.

Calculation: 12 * 1.5 = 18.0.

int(...) converts the floating result 18.0 to the integer 18.

print(...) outputs that integer.

Final output
18

 


Saturday, 8 November 2025

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

 



Code Explanation:

Importing the math module
import math

This imports Python’s built-in math module.

We need it because math.pi gives the value of π (3.14159…).

Defining the Circle class
class Circle:

This starts the definition of a class named Circle.

A class is a blueprint for creating objects.

Initializer method (constructor)
    def __init__(self, r):
        self.r = r

Explanation:

__init__ is called automatically when an object is created.

It receives r (radius).

self.r = r stores the radius in the object’s attribute r.

So, when we do Circle(5),
the object stores r = 5 inside itself.

Creating a readable property: area
    @property
    def area(self):
        return math.pi * self.r**2

Explanation:
@property decorator

Turns the method area() into a property, meaning you can access it like a variable, not a function.

area calculation

Formula used:

Area = π × r²

So:

Area = math.pi * (5)^2
     = 3.14159 * 25
     = 78.5398...

Printing the area (converted to integer)
print(int(Circle(5).area))

Breakdown:

Circle(5) → Creates a Circle with radius = 5.

.area → Gets the computed area property (≈ 78.5398).

int(...) → Converts it to an integer → 78.

print(...) → Prints 78.

Final Output
78

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

 


Code Explanation:

Importing the dataclass decorator
from dataclasses import dataclass

This imports @dataclass, a decorator that automatically adds useful methods to a class (like __init__, __repr__, etc.).

It helps create classes that mainly store data with less code.

Declaring the Product class as a dataclass
@dataclass
class Product:

@dataclass tells Python to automatically create:

an initializer (__init__)

readable string format

comparison methods

The class name is Product, representing an item with price and quantity.

Defining class fields
    price: int
    qty: int

These define the two attributes the class will store:

price → an integer value

qty → an integer quantity

With @dataclass, Python will automatically create:

def __init__(self, price, qty):
    self.price = price
    self.qty = qty

Creating a method to compute total cost
    def total(self):
        return self.price * self.qty

Explanation:

Defines a method named total.

It multiplies the product’s price by qty.

Example: price = 7, qty = 6 → total = 42.

Creating a Product object and printing result
print(Product(7, 6).total())

Breakdown:

Product(7, 6) → Creates a Product object with:

price = 7

qty = 6

.total() → Calls the method to compute 7 × 6 = 42.

print(...) → Displays 42.

Final Output
42


Friday, 7 November 2025

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

 


Code Explanation:

Importing dataclass
from dataclasses import dataclass

Theory:

The dataclasses module provides a decorator and functions to automatically generate special methods in classes.

@dataclass automatically creates methods like:

__init__() → constructor

__repr__() → for printing objects

__eq__() → comparison

This reduces boilerplate code when creating simple classes that mainly store data.

Defining the Data Class
@dataclass
class Item:

Theory:

@dataclass tells Python to treat Item as a data class.

A data class is primarily used to store attributes and automatically provides useful methods.

Declaring Attributes
    price: int
    qty: int

Theory:

These are type-annotated fields:

price is expected to be an int.

qty is expected to be an int.

The dataclass automatically generates an __init__ method so you can create instances with Item(price, qty).

Creating an Object
obj = Item(12, 4)

Theory:

This creates an instance obj of the Item class.

The dataclass automatically calls __init__ with price=12 and qty=4.

Internally:

obj.price = 12
obj.qty = 4

Performing Calculation and Printing
print(obj.price * obj.qty)

Theory:

Accesses the object’s attributes:

obj.price = 12

obj.qty = 4

Multiplies: 12 * 4 = 48

print() displays the result.

Final Output
48

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


 


Code Explanation:

Defining the class
class Squares:

This line defines a new class named Squares.

A class is a blueprint for creating objects and can contain attributes (data) and methods (functions).

Defining the constructor (__init__)
    def __init__(self, nums):
        self.nums = nums

__init__ is the constructor method — it runs automatically when a new object is created.

nums is passed as an argument when creating the object.

self.nums = nums stores the list in the instance variable nums, so each object has its own nums.

Defining a method sum_squares
    def sum_squares(self):
        return sum([n**2 for n in self.nums])

sum_squares is a method of the class.

[n**2 for n in self.nums] is a list comprehension that squares each number in self.nums.
Example: [2,3,4] → [4,9,16]

sum(...) adds all the squared numbers: 4 + 9 + 16 = 29.

The method returns this total sum.

Creating an object of the class
obj = Squares([2,3,4])
This creates an instance obj of the Squares class.

nums = [2,3,4] is passed to the constructor and stored in obj.nums.

Calling the method and printing
print(obj.sum_squares())

obj.sum_squares() calls the sum_squares method on the object obj.

The method calculates: 2**2 + 3**2 + 4**2 = 4 + 9 + 16 = 29

print(...) outputs the result: 29

Final Output
29


Thursday, 6 November 2025

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


 Code Explanation:

Defining the Class
class Box:

This defines a new class called Box.

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

It can contain both data (variables) and behavior (methods).

b    count = 0

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

It’s initialized to 0.

Any change to Box.count affects all objects because it belongs to the class, not any single object.

Defining the Constructor (__init__ method)
    def __init__(self, v):
        self.v = v
        Box.count += v

The __init__ method runs automatically when you create a new Box object.

self.v = v creates an instance variable v, unique to each object.

Box.count += v adds the object’s v value to the class variable count.

This line updates the shared class variable every time a new box is created.

Creating First Object
a = Box(3)

This calls __init__ with v = 3.

Inside __init__:

self.v = 3

Box.count += 3 → Box.count = 0 + 3 = 3.

Creating Second Object
b = Box(5)

This calls __init__ again, with v = 5.

Inside __init__:

self.v = 5

Box.count += 5 → Box.count = 3 + 5 = 8.

Printing the Final Class Variable
print(Box.count)

This prints the final value of the class variable count.

After both objects are created, Box.count = 8.

Final Output
8

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

 


Code Explanation:

1. Importing dataclass
from dataclasses import dataclass

Explanation:

Imports the dataclass decorator from Python’s dataclasses module.

@dataclass helps automatically generate methods like __init__, __repr__, etc.

2. Creating a Data Class
@dataclass
class Item:

Explanation:

@dataclass tells Python to treat Item as a dataclass.

Python will auto-generate an initializer and other useful methods.

3. Declaring Attributes
    name: str
    price: int
    qty: int


Explanation:

These are type-annotated fields.

name → string

price → integer

qty → integer

The dataclass generates an __init__ method using these.

4. Creating an Object
item = Item("Pen", 10, 5)

Explanation:

Creates an instance of Item.

Sets:

name = "Pen"

price = 10

qty = 5

5. Performing Calculation and Printing
print(item.price * item.qty)

Explanation:

Accesses price → 10

Accesses qty → 5

Multiplies: 10 × 5 = 50

Prints 50.

Final Output:

50

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (125) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (250) 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 (205) Data Strucures (13) Deep Learning (53) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (42) Git (6) Google (46) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (166) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (10) PHP (20) Projects (32) Python (1204) Python Coding Challenge (846) Python Quiz (323) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (16) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)