Python Functions
Python Functions
A function in Python is a block of code designed to perform a specific task. By grouping repetitive tasks into functions, you can reuse the same code for different inputs, improving both efficiency and maintainability.
Benefits of Using Functions
- Improves Code Readability: By abstracting complex tasks into named functions, the main code becomes cleaner and easier to read.
- Increases Code Reusability: Once a function is written, it can be called multiple times without needing to rewrite the same code.
Syntax for Python Functions
def function_name(parameters):
"""Docstring (optional)"""
# function body
return value
Types of Functions in Python
There are two main types of functions in Python:
1. Built-in Functions: These are pre-defined functions provided by Python (e.g., print(), len(), input()).
2. User-defined Functions: Functions that you define yourself based on your needs.
Creating and Calling a Function
In Python, functions are created using the def
keyword. After defining the function, it can be called by its name followed by parentheses.
Example of a Simple Function:
def greet():
print("Hello, Welcome to Python!")
greet() # Function call
Output:
Hello, Welcome to Python!
Example: Function to Add Two Numbers:
def add(a: int, b: int) -> int:
"""Returns the sum of two numbers."""
return a + b
# Function call with arguments
result = add(5, 10)
print(f"Sum of 5 and 10 is {result}")
Output:
Sum of 5 and 10 is 15
Python Function with Return
Functions can return values using the return
keyword. This allows you to send back the result of the function to the caller.
Example:
def square(num):
return num * num
print(square(4)) # Function call
Output:
16
Types of Function Arguments
Python supports different types of arguments that can be passed to functions:
1. Default Arguments: Arguments that assume a default value if not provided in the function call.
Example:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("John") # Uses default greeting
greet("Alice", "Good Morning") # Custom greeting
Output:
Hello, John!
Good Morning, Alice!
2. Keyword Arguments: Arguments where you explicitly define the name of the parameter.
Example:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(age=20, name="John") # Using keyword arguments
Output:
Name: John, Age: 20
3. Positional Arguments: Arguments are assigned based on their position in the function call.
Example:
def introduce(name, age):
print(f"Hi, I am {name}, and I am {age} years old.")
introduce("Alice", 25) # Correct order
introduce(25, "Alice") # Incorrect order
Output:
Hi, I am Alice, and I am 25 years old.
Hi, I am 25, and I am Alice years old.
4. Arbitrary Arguments (*args
and **kwargs
):
*args
: Used to pass a variable number of non-keyword arguments.**kwargs
: Used to pass a variable number of keyword arguments.
Example with *args
:
def print_args(*args):
for arg in args:
print(arg)
print_args("Hello", "Welcome", "to", "Python")
Output:
Hello
Welcome
to
Python
Docstrings
Docstrings provide a description of the function’s purpose and are considered good practice. They are written within triple quotes right after the function definition.
Example:
def even_odd(num):
"""Checks if a number is even or odd."""
if num % 2 == 0:
print("Even")
else:
print("Odd")
# Accessing docstring
print(even_odd.__doc__)
Output:
Checks if a number is even or odd.
Recursive Functions
A recursive function is one that calls itself. It is useful for problems that can be broken down into smaller instances of the same problem.
Example: Factorial Calculation:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Output:
120
Passing by Reference and Value
In Python, when you pass an object to a function, you are passing a reference to the object, not a copy. So, changes made to the object inside the function will affect the original object.
Example (Passing a List by Reference):
def modify_list(lst):
lst[0] = 100
lst = [1, 2, 3]
modify_list(lst)
print(lst) # List is modified
Output:
[100, 2, 3]
Python def Keyword
The def
keyword in Python is used to define functions, which are reusable blocks of code designed to perform specific tasks. It is used before a function name, allowing the creation of a user-defined function. The def
keyword is essential for structuring Python code logically by grouping related statements under a function name.
Syntax of def
in Python
def function_name():
# function statements
Purpose of def
Keyword
In Python, def
is not only for defining general functions but also for creating class methods and special member functions like __init__()
. Using def
helps with code reusability, letting developers encapsulate specific logic into functions instead of rewriting code repeatedly.
Applications of def
in Python
Below are examples illustrating the various ways to use the def
keyword in Python:
Defining a Simple Function with No Arguments
Example
def greet():
print("Hello, Python!")
greet()
Output:
Hello, Python!
Creating a Function for Subtraction
This function, subtract
, calculates the difference between two numbers.
def subtract(x, y):
return x - y
result = subtract(15, 5)
print("The difference is:", result)
First Class functions in Python
In programming, first-class objects are treated uniformly, allowing them to be stored in data structures, passed as arguments, and used in control structures. A language that treats functions as first-class objects supports first-class functions. Python, as an example, treats functions as first-class citizens.
Properties of First-Class Functions
- Functions are instances of the
Object
type. - Functions can be stored in variables.
- Functions can be passed as parameters to other functions.
- Functions can be returned from other functions.
- Functions can be stored in data structures like lists or dictionaries.
Examples:
def greet(text):
return text.lower()
print(greet("HELLO"))
whisper = greet
print(whisper("HELLO"))
Assign Function to a Variable in Python
This article explains how to assign a function to a variable in Python. By assigning a function to a variable, we can call that function using the variable name multiple times, enhancing code reusability.
Implementation
To assign a function to a variable, simply use the function name without parentheses ()
. If parentheses are used, it will execute the function immediately, returning None
if no return value is provided.
Syntax:
def func():
# function body
variable = func # assigning function to variable
variable() # calling the function through variable
Example:
def greet():
print("Welcome to Python!")
# Assigning the function to a variable
message = greet
# Calling the function using the variable
message()
message()
Output:
Welcome to Python!
Welcome to Python!
Python User defined functions
A function is a set of instructions designed to take inputs, perform specific calculations, and return an output. The purpose of a function is to consolidate tasks that are commonly or repeatedly performed so that we can call the function instead of duplicating code. Python provides built-in functions, such as print()
, but we can also define our own functions, known as user-defined functions.
Python User-defined Functions
All functions that we write are categorized as user-defined functions. Below are the steps for creating user-defined functions in Python:
- Use the
def
keyword to define a function. - An indented block of statements follows the function name and arguments, forming the function body.
def function_name():
# statements
Example
# Defining a function
def show_message():
print("This is a custom function.")
# Calling the function
show_message()
Output:
This is a custom function.
Python Parameterized Function
A function can accept arguments or parameters as inputs within the parentheses following the function name.
Example:
def check_even_odd(num):
if num % 2 == 0:
print("Even")
else:
print("Odd")
# Calling the function
check_even_odd(4)
check_even_odd(7)
Output:
Even
Odd
Python Default Arguments
A default argument has a value that is assigned if no argument is provided when the function is called.
Example: Here, we call display_info()
with a single argument.
# Function with a default argument
def display_info(name, age=25):
print("Name:", name)
print("Age:", age)
# Calling the function
display_info("Alice")
Output:
Name: Alice
Age: 25
Python Keyword Arguments
Keyword arguments allow the caller to specify argument names with values, so the order of arguments does not need to be memorized.
Example:
def introduce(first_name, last_name):
print(first_name, last_name)
# Calling with keyword arguments
introduce(first_name="John", last_name="Doe")
introduce(last_name="Doe", first_name="John")
Output:
John Doe
John Doe
Python Variable-Length Arguments
We can have variable numbers of arguments, both positional (*args
) and keyworded (**kwargs
).
Example:
def show_args(*args):
for arg in args:
print(arg)
def show_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key} == {value}")
# Calling the functions
print("Result of *args:")
show_args("Hello", "This", "is", "Python")
print("\nResult of **kwargs:")
show_kwargs(name="John", age=30, country="USA")
Output:
Result of *args:
Hello
This
is
Python
Result of **kwargs:
name == John
age == 30
country == USA
Pass by Reference or Pass by Value in Python
In Python, every variable name is a reference. When a variable is passed to a function, a new reference to the object is created. We can use Python’s id()
function to confirm this.
Example:
def show_id(value):
print("Value inside function:", value, "id:", id(value))
# Driver code
num = 42
print("Value outside function:", num, "id:", id(num))
show_id(num)
Output:
Value outside function: 42 id: 139865623584656
Value inside function: 42 id: 139865623584656
Python Function with Return Value
Sometimes a function needs to return a value to the caller, which can be achieved using the return
statement.
Example:
def sum_values(a, b):
return a + b
def check_true(condition):
return bool(condition)
# Calling functions
result = sum_values(5, 3)
print("Result of sum function:", result)
result = check_true(3 > 1)
print("Result of check_true function:", result)
Output:
Result of sum function: 8
Result of check_true function: True
Defining a Python function at runtime
In Python, we can create a function at runtime and execute it using FunctionType()
. This approach involves importing the types
module, using compile()
with exec
mode, and then defining the function at runtime with FunctionType()
.
Example 1: Function to Print “Hello, Python!
# Importing the module
from types import FunctionType
# Defining the function during runtime
code_obj = compile('def hello_func(): return "Hello, Python!"', "<string>", "exec")
runtime_func = FunctionType(code_obj.co_consts[0], globals(), "hello_func")
# Calling the function
print(runtime_func())
Output:
Hello, Python!
Python Built in Functions
Python is versatile in handling system scripting, software development, and web development (server-side). It can manage workflows, connect to databases, modify files, handle big data, and perform advanced mathematical tasks.
The syntax in Python is straightforward and English-like, allowing developers to write concise code compared to other languages. Python’s interpreter system enables code execution immediately upon writing. Python also provides numerous built-in functions that make coding simpler.
In this guide, you will discover Python’s built-in functions, exploring their purposes and applications. Here’s a rundown of some of the most commonly used built-in functions in Python:
- abs(): Returns the absolute value of a number.
abs(-5)
# Output: 5
- aiter(): Creates an asynchronous iterator from an asynchronous iterable.
# Example: (used within an async function)
async for item in aiter(async_iterable):
print(item)
- all(): Returns
True
if all elements in an iterable areTrue
.
all([True, True, False])
# Output: False
- any(): Returns
True
if any element in an iterable isTrue
.
any([False, True, False])
# Output: True
- anext(): Retrieves the next item from an asynchronous iterator.
# Example: (used within an async function)
await anext(async_iterator)
- ascii(): Returns a string with only ASCII characters, escaping non-ASCII characters.
ascii("éclair")
# Output: "'\\xe9clair'"
- bin(): Converts an integer to a binary string.
bin(10)
# Output: '0b1010'
- bool(): Converts a value to a Boolean (
True
orFalse
).
bool(0)
# Output: False
- breakpoint(): Invokes a debugger at the call site.
breakpoint()
# (opens debugger)
- bytearray(): Returns a mutable byte array from a sequence of bytes.
bytearray([65, 66, 67])
# Output: bytearray(b'ABC')
- bytes(): Creates an immutable bytes object.
bytes([65, 66, 67])
# Output: b'ABC'
- callable(): Checks if an object appears callable.
callable(len)
# Output: True
- chr(): Returns a character for a given Unicode code.
chr(97)
# Output: 'a'
- classmethod(): Converts a function to a class method.
class MyClass:
@classmethod
def example(cls):
return "This is a class method."
MyClass.example()
# Output: 'This is a class method.'
- compile(): Compiles source code into a code object.
code_obj = compile("x = 5", "<string>", "exec")
exec(code_obj)
# Output: (x is set to 5)
- complex(): Creates a complex number.
Enter a number: 100
Type before conversion: <class 'str'>
Type after conversion: <class 'int'>
- delattr(): Deletes an attribute from an object.
class MyClass:
x = 10
delattr(MyClass, 'x')
- dict(): Creates a dictionary.
dict(name="John", age=30)
# Output: {'name': 'John', 'age': 30}
- dir(): Returns a list of attributes and methods of an object.
dir([])
# Output: (list of list methods and attributes)
- divmod(): Returns the quotient and remainder of division as a tuple.
divmod(7, 3)
# Output: (2, 1)
- enumerate(): Adds a counter to an iterable, returning an enumerate object.
list(enumerate(['a', 'b', 'c']))
# Output: [(0, 'a'), (1, 'b'), (2, 'c')]