Python Functions Examples
The guide discusses the whole concept of Python functions examples. It encompasses their definitions and syntax. Introductions into built-in functions, user-defined functions, lambda functions, and recursive functions, along with the ideas behind higher-order functions and closures, lead into this section of the guide. This section delves into function parameters, return values, error handling, and decorators. Partial functions, memorization, and optimizing functions will come under advanced topics in this guide. Best practices of the guide regarding documentation with a docstring of the function, writing testable code, and reuse with refactor will be highlighted.
Introduction to Functions in Python
Functions are an integral part of the Python language because they allow clean and efficient code organization and management. You will write your code to be reused numerous times, making it modular and easy to maintain as you develop with functions. In this chapter, we venture into the world of Python functions examples, discussing everything from the basics all the way to sophisticated levels illustrated with examples to really cement your understanding.
What is a Python Function?
A function is an organized, reusable block of code that does one related action. Functions give your application better modularity and a high degree of code reusability. A function in Python is declared using the keyword def followed by the name of the function and parentheses.
Why Functions are Important
Functions: The Building Blocks in Programming
Functions are the basic building blocks in programming. They will cut out redundant code, make your code easier to read, and ease testing and debugging processes. They can also help break hard problems into smaller, manageable pieces.
Defining and Using Functions
Basic Syntax of a Python Function
The general syntax for Python is as follows:
def function_name(parameters):
"""
" docstring " ""
statement(s)
The following is a quick example:
def greet(name ):
""]] BusinessException This function greets the person passed in as a parameter.
print(f"Hello, {name}!")
In this example, greet is the function name, and name is the parameter.
Function Naming Conventions
As you name your functions in Python, do the following:
Use lowercase words separated by underscores, e.g., calculate_sum.
The name should indicate what the function does.
Avoid keywords in the Python language and special characters.
How to Call a Function
Function Call Print the function name and an open parenthesis, followed by any arguments inside the parentheses. Example: print(Hello name: "Alice") This will output: Hello, Alice! Functions in Python Built-in Functions Python has many built-in functions. Some of the most widely used are print(), len(), and type(). Built-in functions are always available and provide basic functionality needed for everyday programming tasks.
You may also write your own functions to perform tasks that make sense in terms of the needs of your application, as shown with the keyword def above.
When it comes to Python coding then, Python code has the capability to be compiled using online compilers that are akin to Python Online Compiler.
Anonymous (Lambda) Functions
A Lambda function is a small anonymous function defined using the keyword lambda. They can be useful when working with single operations:
square = lambda x: x * x
print(square(5))
This would print:
.
Understanding Function Parameters
Positional Arguments
Most common types of arguments in Python are positional arguments, in which the function arguments are passed based on the defined order.
)nosecdef add(a, b):
return a + b
print(add(3, 5))
Output:
A parameter is an optional one when we use default parameters. In this case, the default value is used whenever the caller omits its value.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", "Hi")
This will output:
Hello, Alice!
Hi, Bob!
Variable-length Arguments
Python allows functions to accept an arbitrary number of arguments using *args and **kwargs.
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5))
This will output
15
Return Statements in Functions
Returning Values
You can return a value from a function with the return statement. If no return statement is given, a function returns None.
def square(x):
return x * x
print(square(4))
END
Python functions can return multiple values as a tuple:
def get_full_name(first_name, last_name):
return first_name, last_name
print(get_full_name("John", "Doe"))
This would print
It would be very confusing indeed, if variables inside a function behaved differently from those defined at module level. A local variable is one that is defined inside a function. A global variable is one that is defined outside any function.
x = 10 # global variable
def example():
x = 5 # local variable
print(x)
example()
print(x)
This would print
ends
5
10
The global Keyword
The Global Keyword
The global keyword lets you access a global variable inside a function.
xampp/config/cp.php
x = 10
\
def change_global():
global x
x = 20
change_global()
print(x)
This would print:
20
The Nonlocal Keyword
The nonlocal keyword is used with nested functions to refer to a variable in the nearest enclosing scope.
xampp/config/cp.php
def outer():
x = "local"
print()
print()
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
Would print:
inner: nonlocal
outer: nonlocal
Decorators and Higher-Order Functions
Introduction to Decorators
A decorator is a function that takes another function and modifies its behavior. They can enhance the reusability of a piece of code and add functionality to existing code without having to modify it.
They are used in defining a small function that can modify or extend the behavior of some other function.
print("Function is about to run")
func()
print("Function has finished running")
return wrapper
@decorator_function
def say_hello():
print("Hello!")
say_hello()
This would print:
vbnet
Function is about to run
Hello!
Function has finished running
Creating a Decorator
Writing a decorator entails building a function that returns yet another function-the decorator.
Higher-Order Functions
A higher-order function is one that either takes another function as an argument or returns a function as output.
Handling Errors in Functions
Try and Except Blocks
Python error handling is achieved using try and except blocks. This line above allows the program to gracefully handle exceptions.
return "Cannot divide by zero"
print(divide(10, 2))
print(divide(10, 0))
This would print:
5.0
Cannot divide by zero
Raising Exceptions in Functions
You can raise exceptions in functions by the keyword raise.
End
return x
print(check_value(10))
# print(check_value(-10)) # This would raise an exception
Custom Exceptions
Custom exceptions can be defined by inheriting from the Exception class.
class CustomError(Exception):
pass
def check_value(x):
if x < 0:
raise CustomError("Value cannot be negative")
return x
Recursive Functions
What is Recursion?
It recurs when a function calls itself in its computation. It can be used on any problem which can be divided into related sub-problems.
Base Case and Recursive Case
The base case is considered as a recursive function if it will attempt to complete the job without recursion so that infinite loops do not happen.
EG:
\def factorial(n):
if n == 1:
back 1
else:
return n * factorial(n - 1)
print(factorial(5))
This would give you the output :
120
Applications of Recursive Functions
Recursion is widely used in algorithms like calculating the factorial of a number, to produce the Fibonacci sequence and to perform tree traversal.
Functions as First-Class Objects
Functions in Lists and Dictionaries
In Python, functions can be assigned to lists and dictionaries-in the real meaning of the word, they can therefore be passed around like just any other object.
Some day soon you'll want to write very large programs. Larger than you can keep in your head at one time, that is. At such time you may very well want to encapsulate groups of related operations inside a function definition. In short you'll want to write something like this: def add(a, b): return a + b
def subtract(a, b):
return a - b
operations = {
"add": add,
"subtract": subtract
}
print(operations["add"](5, 3))
Output
Passing Functions as Arguments
Functions can be passed as arguments to other functions.
def apply_operation(func, x, y):
return func(x, y)
print(apply_operation(add, 10, 5))
This would output:
15
Returning Functions from Functions
Functions can also return other functions.
def create_multiplier(n):
def multiplier(x):
return x * n
return multiplier
times_three = create_multiplier(3)
print(times_three(5))
This would output:
15
Anonymous Functions and Lambda Expressions
Syntax of Lambda Functions
Lambda functions are a way to express small, anonymous functions in Python. They are defined using the lambda keyword.
\\ Petite = lambda x: x \* 2
print(Petite(5))
This would print:
10
When to Use Lambda Functions
Lambda functions should be used for short operations or when you need a quick definition of a function, without the name.
Limitations of Lambda Functions
As they can hold only one statement but cannot hold multi-statements or comments.
Inbuilt Functions in Python: Real World Applications
The len() Function
The len() function returns the number of items in a given object like a list, string, or dictionary.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x : x * x, numbers))
print(squared)
This would print:
csharp
[1, 4, 9, 16, 25]
The filter() Function
The filter() function filters items in an iterable based on a condition.
`python
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
This would output:
csharp
[2, 4]
The reduce() Function
The reduce() function performs a rolling computation applied to successive pairs of values in a list -- to reduce the list onto a single output. This is analogous to functional programming's foldl.
from functools import reduce
from itertools import product
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
This would print:
120
More Advanced Function Techniques
Partial Functions
Partial functions let you bind a certain number of arguments of a function and return a new function.
from functools import partial
add_five = partial(add, 5)
print(add_five(10))
This will print:
15
Closures in Python
A closure is a function object that remembers values in the enclosing scopes, even if they are not present in memory.
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
hello_func = outer_function("Hello")
hello_func()
This would print:
Hello
Memoization and Caching Functions
Memoization is an optimization technique, utilizing memoization of expensive function calls to cache them and reuse those values when the same inputs occur again.
from functools import lru_cache @
lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
This would print:
55
Optimizing Functions to Gain Efficiency
Time Complexity
While you are coding, the time complexity of a function is critical. Functions with lower time complexities are quicker and scale better.
Proiling Your Python Functions
Tools such as cProfile can help you to measure the efficiency of your functions to pinpoint bottle-necks
Writing Function Efficiently
Never perform redundant calculations inside loops
Use list comprehensions to gain better performance
Always depend on built-in functions in Python; these are faster compared to a hand-implemented version.
Best Practices Writing Python Functions
Docstrings
A docstring gives an indication of what a function does, what parameters it takes, and what it returns. This is good for code quality and readability.
ends.
int: The sum of param1 and param2.
"""
end
return param1 + param2
Creating Testable Functions
Ensure that the code you write is readable and modular enough to be tested easily by frameworks such as unittest or pytest.
Refactor Function
It means minimizing duplication, reuse, redo. Often, it's helpful to break big methods into smaller ones sometimes.
FAQs
1. What's the difference between a method and a function in Python?
A function is a piece of code that does a specific task and is called on its own, whereas a method is the function belonging to a class and a message is passed on it.
2. Do functions defined in Python return more than one value?
Yes, functions defined in Python can return more than one value returning them as a tuple which can then be unpacked into different variables.
3. What are the uses for lambda functions?
Lambda functions. They are for small, anonymous operations, passed to other higher-order functions such as map(), filter(), and reduce(), etc.
4. How do I make my Python code run faster?
This is achieved by optimizing the algorithm for the function in Python, using intrinsic functions, avoiding useless loops, and maybe using tools to profile your code with cProfile, etc.
5. What is recursion and when should I use it?
Now recursion. This is a call in a function. Recursion is good for problems that can be split down into more and more similar subproblems, such as the explicit tree traversal or factors calculation.
6. Python decorators-How do they work?
Decorators are functions that take functions and return other functions. It can be used for addition of any existing code without changing that code.