Functions in Python: Definition, Examples, and Best Practices

What is a Function in Python?

A function in Python is a reusable block of code that takes inputs, performs operations, and returns outputs. Python includes many built-in functions like math.sqrt(x) or math.sin(x) that process inputs and provide results.

One of Python’s most powerful features is the ability to create your own functions using the def keyword.

def function_name(argument1, argument2, ...):
    function_body
    return output
  • Arguments: the inputs to the function
  • Function body: the indented block of code
  • Return value: the output produced

Example: Defining a Polynomial Function

Let’s define f(x) = 3x² − 5x + 4:

def polynomial(x):
    output = 3*x**2 - 5*x + 4
    return output

Example: Function with Multiple Arguments

Functions can take several inputs. For example, a function that sums three numbers:

def sum_three(a, b, c): 
    output = a + b + c
    return output

Calling Functions in Python

To call a function, use its name with arguments:

print(polynomial(3))  # Output: 16

y = polynomial(3)  
print(y)  # Output: 16

With multiple arguments:

print(sum_three(3, 4, 5))  # Output: 12

Local vs. Global Variables in Functions

Variables defined inside functions are local variables, while those outside are global variables.

Example of local scope:

def sum_three(a, b, c): 
    output = a + b + c
    return output

sum_three(1, 2, 3)
print(output)  # Error: output is local

Using global makes a variable accessible everywhere:

def sum_three(a, b, c): 
    global output
    output = a + b + c
    return output

sum_three(1, 2, 3)
print(output)  # Prints 6

Input Arguments and Keyword Arguments

When calling functions, you can define arguments by name:

print(sum_three(a=3, b=4, c=1))  # Output: 8

Keyword arguments also allow flexibility in order:

print(sum_three(c=1, a=3, b=4))  # Output: 8

Return Parameters in Python Functions

The return statement sends values back from a function. Functions can return one or multiple values:

def operations(a, b):
    sum_val = a + b
    product = a * b
    return sum_val, product

s, p = operations(3, 4)
print(s, p)  # Output: 7 12

Summary of Python Functions

  • Functions are reusable blocks of code defined with def.
  • Inputs are passed as arguments; outputs are produced with return.
  • Local variables only exist inside functions; global variables exist everywhere.
  • Keyword arguments allow flexibility in argument order.
  • Functions can return one or more values.

Leave a Comment

Your email address will not be published. Required fields are marked *