Python functions are essential building blocks in programming, allowing you to group code into reusable units. This tutorial will cover the basics of Python functions, including their syntax, types, and how to use them effectively.
A function in Python is a block of code that performs a specific task. Functions help in organizing code, improving readability, and reusability. Instead of repeating code, you define a function once and call it whenever needed. Functions can take inputs (arguments), process them, and return outputs.
Functions in Python can be categorized into two main types:
1. Built-in Functions: Provided by Python itself (e.g., print(), len()).
2. User-Defined Functions: Created by the user to perform specific tasks.
1. Reusability: Once a function is defined, it can be called multiple times from anywhere in the code.
2. Modularity: Break down a complex program into smaller, manageable functions.
3. Maintainability: Easier to manage and update code in one place rather than modifying multiple code blocks.
4. Flexibility: Functions can return values and accept a variety of argument types.
The syntax for defining a function is as follows
def function_name(parameters):
# code block
return result
• def: Keyword to define a function.
• function_name: The name of the function.
• parameters: (Optional) Inputs to the function.
• :: Indicates the start of the function body.
• return: (Optional) Sends a result back to the caller.
Here’s an example of a simple user-defined function that computes the cube of a number:
def cube(num):
"""
This function computes the square of the number.
"""
return num ** 3
result = cube(5)
print("The cube of the given number is:", result)
The cube of the given number is: 125
To call a function, simply use its name followed by parentheses. If the function requires arguments, pass them inside the parentheses.
def print_length(string):
"This prints the length of the string"
return len(string)
print("Length of the string 'Functions' is:", print_length("Functions"))
print("Length of the string 'Python' is:", print_length("Python"))
Length of the string 'Functions' is: 9
Length of the string 'Python' is: 6
Functions in Python can accept various types of arguments:
Arguments that take a default value if none is provided.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Uses default value
greet("Alice") # Uses provided value
def greet(name="Guest"):
print("Hello", name)
greet() # Uses default value
greet("Alice") # Uses provided value
Arguments specified by name.
def display_info(name, age):
print(f"Name: {name}, Age: {age}")
display_info(name="Bob", age=25)
Name: Bob, Age: 25
Must be provided in the correct order.
def add(a, b):
return a + b
print(add(3, 5))
8
*args: Allows passing a variable number of positional arguments.
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4))
10
**keywordargs: Allows passing a variable number of keyword arguments.
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Charlie", age=30)
name: Charlie
age: 30
The return statement exits a function and optionally passes a value back to the caller.
def multiply(x, y):
return x * y
result = multiply(4, 5)
print("Product is:", result)
add = lambda x, y: x + y
print("Sum is:", add(10, 20))
Sum is: 30
Variables defined inside a function are local to that function and cannot be accessed outside. The lifetime of these variables is limited to the execution of the function.
def example():
num = 50
print("Inside function:", num)
num = 10
example()
print("Outside function:", num)
Inside function: 50
Outside function: 10
Functions in Python are first-class objects, meaning they can be defined inside other functions.
def outer_function():
def inner_function():
print("This is the inner function.")
inner_function()
outer_function()
This is the inner function.
This overview should give you a solid understanding of Python functions and how to use them effectively in your programs.