Defining and Calling Functions in Python

Functions are blocks of reusable code in Python that perform a specific task. Defining and calling functions is a fundamental concept in programming, promoting code modularity and reusability.

1. Defining a Function:

To define a function, use the def keyword followed by the function name and a pair of parentheses. If the function takes parameters, list them within the parentheses.

# Example of a simple function without parameters
def greet():
    print("Hello, welcome!")

# Example of a function with parameters
def add_numbers(a, b):
    sum_result = a + b
    return sum_result

2. Calling a Function:

To call a function, use its name followed by parentheses. If the function takes parameters, provide them within the parentheses.

# Calling the greet function

# Calling the add_numbers function
result = add_numbers(3, 5)
print("Sum:", result)

3. Function Parameters:

Functions can take parameters, allowing them to work with different data each time they are called.

# Function with parameters
def multiply(a, b):
    result = a * b
    return result

# Calling the multiply function
product = multiply(4, 6)
print("Product:", product)

4. Return Statement:

The return statement is used to exit a function and return a value. Functions can return a single value or multiple values as a tuple.

# Function with a return statement
def square(x):
    return x ** 2

# Calling the square function
result = square(4)
print("Square:", result)

5. Default Parameters:

Functions can have default values for parameters, allowing for flexibility in function calls.

# Function with default parameters
def power(base, exponent=2):
    return base ** exponent

# Calling the power function with and without specifying the exponent
result1 = power(3)
result2 = power(3, 4)

print("Default Exponent:", result1)
print("Custom Exponent:", result2)

6. Variable-Length Arguments:

Functions can accept a variable number of arguments using the *args syntax.

# Function with variable-length arguments
def sum_values(*args):
    total = sum(args)
    return total

# Calling the sum_values function with different numbers of arguments
result1 = sum_values(1, 2, 3)
result2 = sum_values(4, 5, 6, 7)

print("Sum 1:", result1)
print("Sum 2:", result2)

7. Conclusion:

Defining and calling functions is a fundamental skill in Python programming. Functions allow you to encapsulate functionality, promote code reuse, and enhance the overall structure of your code.

In the next sections, we’ll explore more advanced topics and practical applications of functions in Python.