Arguments

Wed 15 April 2026
def user_profile(name, *args, **kwargs):
    """Creates a user profile using unpacked arguments."""
    print(f"User: {name}")

    # *args is treated as a tuple of positional arguments
    if args:
        print("Additional skills:", ", ".join(args))

    # **kwargs is treated as a dictionary of keyword arguments
    if kwargs:
        for key, value in kwargs.items():
            print …

Category: python-concepts

Read More

Asynchronous Programming

Wed 15 April 2026
import asyncio

async def say_hello():
    print("Hello, World!")
    await asyncio.sleep(1)
    print("Goodbye, World!")

await(say_hello())
Hello, World!
Goodbye, World!
import asyncio

async def task1():
    print("Task 1 starting...")
    await asyncio.sleep(2)
    print("Task 1 done!")

async def task2():
    print("Task 2 starting...")
    await asyncio.sleep(1)
    print …

Category: Asychronous Programming

Read More

Comprehensions

Wed 15 April 2026
# The traditional way to square even numbers
numbers = [1, 2, 3, 4, 5, 6]
squared_evens = []
for n in numbers:
    if n % 2 == 0:
        squared_evens.append(n ** 2)

# The intermediate "Pythonic" way using a List Comprehension
squared_evens_comp = [n ** 2 for n in numbers if n % 2 == 0]
print(f"List Comprehension …

Category: python-concepts

Read More

Context Managers

Wed 15 April 2026
from contextlib import contextmanager

@contextmanager
def managed_resource(resource_name):
    """A custom context manager for handling a resource."""
    print(f"Acquiring resource: {resource_name}")
    resource = {"name": resource_name, "status": "active"}

    try:
        # Hand the resource over to the 'with' block
        yield resource 
    finally:
        # This block always executes, even if an error occurs above
        print(f …

Category: python-concepts

Read More

Cricket Match

Wed 15 April 2026
# pylint: disable=missing-function-docstring, pointless-string-statement, missing-class-docstring

#Gonna try this using the game of chess

"""
@author: Shankar P

"""

import random
import time

canadian_player_names = [
    "Akhil Kumar",
    "Jaskaran Singh",
    "Shreyas Movva",
    "Saad Bin Zafar"
]

australian_player_names = [
    "Tim David",
    "Cummins",
    "Green"
]

team_a_name = "Canada"
team_b_name = "Australia"

# Cricket Constants
SLEEP_GAP_SECONDS = 0.7
OVERS_PER_INNINGS = 2

def get_random_player_name():

    return random …

Category: python-cricket

Read More

Data Classes

Wed 15 April 2026
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

person = Person(name="Alice", age=30)
print(person)  # Output: Person(name='Alice', age=30)
Person(name='Alice', age=30)
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    price: float = 9.99

book = Book(title="Python 101 …

Category: Data Classes

Read More

Decorators

Wed 15 April 2026
import time

def timer_decorator(func):
    """A decorator that prints the execution time of the function."""
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function '{func.__name__}' executed in {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def process_data():
    # Simulating a time-consuming …

Category: python-concepts

Read More

Descriptor Protocols

Wed 15 April 2026
class Descriptor:
    def __get__(self, instance, owner):
        print("Getting value")
        return instance._value

    def __set__(self, instance, value):
        print("Setting value")
        instance._value = value

class MyClass:
    attribute = Descriptor()

obj = MyClass()
obj.attribute = 42  # Setting value
print(obj.attribute)  # Getting value, Output: 42
Setting value
Getting value
42
class ReadOnlyDescriptor:
    def …

Category: Descriptor Protocols

Read More

Exception Handling

Wed 15 April 2026
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero."
    except TypeError:
        return "Inputs must be numbers."
    else:
        return f"Result: {result}"

print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, "x"))

Score: 0

Category: python-concepts

Read More
Page 1 of 2

Next »