Python function

In Python, a function is a block of reusable code that performs a specific task. Functions are defined using the def keyword, followed by the function name, parentheses (), and a colon :. Optionally, functions can take parameters, return values, and include a return statement to pass back a result.

1. Defining a Function

Syntax:


def function_name(parameters):
    # write code block (body of the function)
    return some_value  # (optional)

2. Calling a Function

To call (or invoke) a function, you simply use its name followed by parentheses. If the function accepts parameters, you pass them inside the parentheses.


function_name(arguments)  # Call the function

Example1: Function without Parameters


def greet():
    print("Hello, world!")

greet()  # Function call

Output:

Hello, world!

Example 2: Function with Parameters


def greet(name):
    print(f"Hello, {name}!")

greet("John")  # Function call with an argument

Output:

Hello, John!

Example 3: Function with Return Value


def sumNumbers(a, b):
    return a + b

result = sumNumbers(10, 5)  # Function call and storing the return value
print(result)

Output:

15

Explanation: The sumNumbers function takes two arguments (a and b), adds them, and returns the result. The returned value is stored in result, which is then printed.

Example 4: Function with Default Parameters

You can define functions with default parameter values. If you don’t provide arguments for these parameters, the default values will be used.


def greet(name="John"):
    print(f"Hello, {name}!")

greet()  # Uses default parameter
greet("Tom")  # Overrides default parameter

Output:

Hello, John!
Hello, Tom!

Example 5: Function with Multiple Return Values

Python allows a function to return multiple values as a tuple.


def get_dimensions():
    length = 7
    width = 5
    return length, width  # Returning multiple values

l, w = get_dimensions()  # Unpacking the returned values
print(f"Length: {l}, Width: {w}")

Output:

Length: 7, Width: 5

Example 6: Function with Keyword Arguments

When calling a function, you can specify arguments by name, which allows you to pass them in any order.


def person(name, age):
    print(f"{name} is {age} years old.")

person(name="John", age=35)  # Keyword arguments

Output:

John is 35 years old.