Tutorials Logic, IN info@tutorialslogic.com

Python Functions def, args, kwargs, return

Python Functions def, args, kwargs, return

Python in Python is best learned by connecting the rule to an automation script. Start with the smallest function or script, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch input value and returned object as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

What is a Function?

A function is a reusable block of code that performs a specific task. Functions help you avoid repetition, organize code, and make it easier to test and maintain.

Defining and Calling Functions

Basic Functions

Basic Functions
# Define a function
def greet():
    print("Hello, World!")

# Call the function
greet()   # Hello, World!

# Function with parameters
def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")   # Hello, Alice!
greet_user("Bob")     # Hello, Bob!

# Function with return value
def add(a, b):
    return a + b

result = add(3, 5)
print(result)   # 8

Parameters and Arguments

Parameter Types

Parameter Types
# Default parameters
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")              # Hello, Alice!
greet("Bob", "Hi")          # Hi, Bob!
greet("Charlie", greeting="Hey")  # Hey, Charlie!

# Keyword arguments - order doesn't matter
def describe(name, age, city):
    print(f"{name}, {age}, from {city}")

describe(age=25, city="London", name="Alice")

# *args - variable number of positional arguments
def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))        # 6
print(total(10, 20, 30, 40)) # 100

# **kwargs - variable number of keyword arguments
def show_info(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

show_info(name="Alice", age=25, city="London")

# Combining all parameter types
def full_example(pos, /, normal, *, kw_only, **kwargs):
    print(pos, normal, kw_only, kwargs)

Return Values

Return Values

Return Values
# Return multiple values (as a tuple)
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 4, 1, 5, 9])
print(low, high)   # 1 9

# Early return
def is_even(n):
    if n % 2 == 0:
        return True
    return False

# Functions without return return None
def say_hi():
    print("Hi!")

result = say_hi()
print(result)   # None

# Return a function (higher-order function)
def multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = multiplier(2)
triple = multiplier(3)
print(double(5))   # 10
print(triple(5))   # 15

Type Hints

Type hints (Python 3.5+) make your code more readable and help IDEs catch bugs. They're optional but highly recommended.

Type Hints

Type Hints
def add(a: int, b: int) -> int:
    return a + b

def greet(name: str, times: int = 1) -> str:
    return (f"Hello, {name}! " * times).strip()

def process(items: list[int]) -> dict[str, int]:
    return {"sum": sum(items), "count": len(items)}

# Optional type (can be None)
from typing import Optional

def find_user(user_id: int) -> Optional[str]:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)   # returns str or None

print(find_user(1))   # Alice
print(find_user(99))  # None

Docstrings

Documenting Functions

Documenting Functions
def calculate_area(radius: float) -> float:
    """
    Calculate the area of a circle.

    Args:
        radius (float): The radius of the circle.

    Returns:
        float: The area of the circle.

    Raises:
        ValueError: If radius is negative.

    Example:
        >>> calculate_area(5)
        78.53981633974483
    """
    import math
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

# Access the docstring
print(calculate_area.__doc__)
help(calculate_area)

Recursion

A function that calls itself. Every recursive function needs a base case to stop.

Recursion

Recursion
# Factorial: n! = n * (n-1) * ... * 1
def factorial(n: int) -> int:
    if n <= 1:       # base case
        return 1
    return n * factorial(n - 1)  # recursive call

print(factorial(5))   # 120
print(factorial(10))  # 3628800

# Fibonacci sequence
def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print([fibonacci(i) for i in range(10)])
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Applied guide for Python

Use Python when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real Python task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working function or script, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with traceback and printed inspection. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why Python is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.

  • Identify the exact problem solved by Python.
  • Trace input value and returned object before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to an automation script so the idea feels concrete.
Key Takeaways
  • I can explain where Python fits inside an automation script.
  • I can point to the exact input value and returned object affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with traceback and printed inspection instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace input value and returned object through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small function or script that demonstrates Python in an automation script.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. You can use both: def func(*args, **kwargs). They allow functions to accept any number of arguments.

A decorator is a function that takes another function and extends its behavior. Applied with @decorator_name syntax. Common uses: @staticmethod, @classmethod, @property, @functools.lru_cache for memoization.

A function is defined at module level with def. A method is a function defined inside a class. Methods automatically receive the instance (self) or class (cls) as the first argument.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.