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(f"{key.capitalize()}: {value}")

# Calling the function with a mix of arguments
user_profile(
    "Alice", 
    "Python", "SQL", "Machine Learning", # These become *args
    location="Madurai", role="Data Engineer", active=True # These become **kwargs
)

Score: 0

Category: python-concepts


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

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

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

Generators

Wed 15 April 2026
def fibonacci_generator(limit):
    """Generates Fibonacci numbers up to a specified limit."""
    a, b = 0, 1
    count = 0
    while count < limit:
        yield a
        a, b = b, a + b
        count += 1

# Iterating through the generator
# This uses very little memory, even if the limit was 1,000,000
for number in fibonacci_generator …

Category: python-concepts

Read More

Lambda Functions

Wed 15 April 2026
numbers = [1, 2, 3, 4, 5, 6]

# Use lambda with filter to keep even numbers
evens = list(filter(lambda n: n % 2 == 0, numbers))

# Use lambda with map to square each even number
squared_evens = list(map(lambda n: n ** 2, evens))

print("Even numbers:", evens)
print("Squared evens:", squared_evens)

Score …

Category: python-concepts

Read More

Properties

Wed 15 April 2026
class Temperature:
    def __init__(self, celsius):
        # We use an underscore to indicate this is an internal variable
        self._celsius = celsius

    @property
    def celsius(self):
        """The getter method."""
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        """The setter method, allowing for validation."""
        if value < -273.15:
            raise ValueError("Temperature cannot …

Category: python-concepts

Read More

Recursion

Wed 15 April 2026
def factorial(n):
    if n < 0:
        raise ValueError("n must be a non-negative integer")
    if n in (0, 1):
        return 1
    return n * factorial(n - 1)

for value in range(6):
    print(f"factorial({value}) = {factorial(value)}")

Score: 0

Category: python-concepts

Read More
Page 1 of 1