Python Functions

What are Functions?

A function is a block of code that performs a specific task. Functions are used to break up code into manageable pieces and to avoid repetition. Python comes with built-in functions like print() and len(), but you can also define your own.

Example of a built-in function:

print("Hello, Philippines!")  # This is a built-in function

Defining a Function

You define a function in Python using the def keyword, followed by the function name, parentheses ( ), and a colon :. Inside the function, you write the block of code that will run when the function is called.

Syntax:

def function_name():
    # Code to execute

Example:

def welcome():
    print("Welcome to the Philippines!")

To call a function (i.e., execute the code within it), you simply use its name followed by parentheses:

def welcome():
    print("Welcome to the Philippines!")
    
welcome()  # Output: Welcome to the Philippines!

Arguments and Parameters

Functions can accept arguments, which allow you to pass data into the function. When defining a function, the variables listed in the parentheses are called parameters. When calling the function, the actual values passed in are called arguments.

Example:

def greet(name):  # 'name' is the parameter
    print(f"Hello, {name}!")

greet("Maria")  # 'Maria' is the argument

 

Positional Arguments: 

The arguments are passed in the order in which the parameters are defined.

def add(x, y):
    return x + y

result = add(3, 5)  # Arguments 3 and 5 are passed in positional order
print(result)  # Output: 8

 

Keyword Arguments: 

You specify which argument corresponds to which parameter, regardless of their order.

def add(x, y):
    return x + y

result = add(y=5, x=3)  # Keyword arguments allow specifying values by their parameter names
print(result)  # Output: 8

 

Default Parameters: 

You can set default values for parameters. If no argument is provided when the function is called, the default value will be used.

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

greet()         # Output: Hello, Guest!
greet("Maria")  # Output: Hello, Maria!

return Statement

The return statement allows a function to send a value back to the caller. This lets the function pass data back to the part of the program that called it. Once a return statement is executed, the function terminates.

Example:

def add(x, y):
    return x + y

result = add(4, 5)
print(result)  # Output: 9

A function without a return statement will return `None` by default.

Local vs Global Scope

The scope of a variable refers to the region of the code where that variable can be accessed. Variables defined inside a function are said to be in the local scope and can only be accessed within that function. Variables defined outside any function are in the global scope and can be accessed anywhere in the code.

Example:

x = 10  # Global variable

def example():
    y = 5  # Local variable
    print(x)  # Accessing global variable inside a function
    print(y)  # Accessing local variable

example()
print(x)  # Output: 10
# print(y) would raise an error, as y is not accessible outside the function

You can modify a global variable inside a function by using the global keyword, though it’s generally better practice to avoid this in most cases.

Example:

x = 10

def modify_global():
    global x
    x = 20

modify_global()

print(x)  # Output: 20

Importing Modules

Modules are files containing Python code, which can include functions, variables, and classes. You can import a module into your script using the `import` keyword, which gives you access to its functionality.

Example:

import math  # Importing the math module

print(math.sqrt(16))  # Using a function from the math module, Output: 4.0

You can also import specific functions or objects from a module:

from math import sqrt

print(sqrt(25))  # Output: 5.0

To give an imported module a custom name (an alias):

import math as m

print(m.pi)  # Output: 3.141592653589793

Modules make it easy to reuse code across different programs, and Python comes with a large standard library of built-in modules.

Scroll to Top