0% found this document useful (0 votes)
3 views12 pages

Function Notes

The document provides a comprehensive overview of functions in Python, detailing their definition, usage, and various types of parameters and arguments. It explains key concepts such as calling functions, return values, default parameters, and the distinction between parameters and arguments. Additionally, it highlights the importance of functions for code reusability, modularity, maintainability, and readability.

Uploaded by

reddisandeep92
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views12 pages

Function Notes

The document provides a comprehensive overview of functions in Python, detailing their definition, usage, and various types of parameters and arguments. It explains key concepts such as calling functions, return values, default parameters, and the distinction between parameters and arguments. Additionally, it highlights the importance of functions for code reusability, modularity, maintainability, and readability.

Uploaded by

reddisandeep92
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

Fuction:

Functions in Python are blocks of reusable code that perform a specific task. They help organize
code into manageable, modular components, making it easier to understand, maintain, and reuse.
Here's a deeper look into what functions are and how they work in Python:

Key Concepts

1. Definition: Functions are defined using the def keyword followed by the function name
and parentheses. If the function has parameters, they are listed inside the parentheses. The
function's code block starts with a colon.

python
Copy code
def function_name(parameters):
# code block
pass # placeholder statement

2. Calling a Function: To execute the code inside a function, you call it by using its name
followed by parentheses. If the function requires arguments, you provide them inside the
parentheses.

python
Copy code
function_name(arguments)

3. Parameters and Arguments:


o Parameters are variables listed inside the parentheses in the function definition.
They act as placeholders for the values that will be passed to the function.
o Arguments are the actual values passed to the function when it is called.

python
Copy code
def greet(name):
print(f"Hello, {name}!")

greet("Alice") # "Alice" is an argument

4. Return Values: Functions can return values using the return keyword. If no return
statement is present, the function returns None by default.

python
Copy code
def add(a, b):
return a + b

result = add(3, 5) # result is 8

5. Default Parameters: You can provide default values for parameters. If an argument is
not provided for that parameter when the function is called, the default value is used.

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

greet() # "Hello, Guest!"


greet("Bob") # "Hello, Bob!"

6. Variable-Length Arguments:
o *args: Allows you to pass a variable number of positional arguments to a
function.
o **kwargs: Allows you to pass a variable number of keyword arguments to a
function.

python
Copy code
def print_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

print_info(1, 2, 3, name="Alice", age=30)

7. Lambda Functions: These are small, anonymous functions defined with the lambda
keyword. They can have any number of parameters but only one expression.

python
Copy code
square = lambda x: x * x
print(square(4)) # 16

Example of a Function

Here's a full example that demonstrates some of these concepts:

python
Copy code
def multiply(x, y=1):
"""
Multiplies two numbers. The second number defaults to 1 if not provided.
"""
return x * y

result1 = multiply(5, 2) # Both arguments provided


result2 = multiply(7) # Only one argument provided, y defaults to 1

print(result1) # Output: 10
print(result2) # Output: 7

Why Use Functions?

 Reusability: Write once, use many times.


 Modularity: Break down complex problems into simpler, manageable pieces.
 Maintainability: Easier to update and fix bugs in isolated parts of the code.
 Readability: Makes code more readable by abstracting complex logic into named
functions.

Functions are fundamental to writing clean, efficient, and maintainable Python code.

Creating a Function:

def my_function():
print("Hello from a function")
Explanation

Function Definition:

def is the keyword used to define a function.

my_function is the name of the function.

Function names should be descriptive and follow naming conventions


(e.g., my_function is a good practice, while myFunc or myfunction
might be less clear).
The parentheses () follow the function name.

Since this function doesn’t take any parameters, they are empty.

The colon : indicates the start of the function body.

Function Body:

The line print("Hello from a function") is the body of the function.

This is the code that runs when the function is called.

print("Hello from a function")

prints the string "Hello from a function" to the console.

Calling the Function

To execute the code inside the function, you need to call the function using its name followed by
parentheses:

def my_function():

print("Hello from a function") # Calling the function my_function()

In Python, arguments are the values you pass to a function when you call it. These arguments
provide the function with the data it needs to perform its task. Let's delve into the different types
of arguments you can use in Python functions:

Arguments:

1. Positional Arguments

Positional arguments are the most common type of arguments. They are passed to the function in
a specific order. The function assigns these arguments to the parameters based on their position.

Example
python
Copy code
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet("Alice", 30)

In this example:

 "Alice" is assigned to name.


 30 is assigned to age.

2. Default Arguments

Default arguments allow you to provide default values for parameters. If no argument is
provided for those parameters when the function is called, the default value is used.

Example
python
Copy code
def greet(name="Guest", age=25):
print(f"Hello, {name}! You are {age} years old.")

greet() # Uses default values


greet("Bob") # Uses default value for age
greet("Charlie", 40) # Overrides both default values

In this example:

 If no arguments are provided, name defaults to "Guest" and age defaults to 25.
 If only one argument is provided, name is set to that value and age uses the default value.
 If both arguments are provided, they override the default values.

3. Keyword Arguments

Keyword arguments are specified by explicitly stating the parameter names along with their
values when calling the function. This allows for greater flexibility and clarity.

Example
python
Copy code
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet(age=30, name="Alice") # The order of arguments can be different

Here, the order of arguments does not matter because they are specified by name.
4. Arbitrary Positional Arguments (*args)

If you don’t know how many arguments might be passed to your function, you can use *args to
collect them into a tuple. This allows the function to handle a variable number of positional
arguments.

Example
python
Copy code
def print_numbers(*args):
for num in args:
print(num)

print_numbers(1, 2, 3, 4, 5)

In this example, *args collects all positional arguments into a tuple, which is then iterated
over in the function body.

5. Arbitrary Keyword Arguments (**kwargs)

Similarly, if you need to handle a variable number of keyword arguments, you can use
**kwargs to collect them into a dictionary.

Example
python
Copy code
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=30, city="New York")

In this example, **kwargs collects all keyword arguments into a dictionary, which is then
iterated over to print the key-value pairs.

6. Combination of Arguments

You can combine different types of arguments in a function definition, but there is a specific
order they must follow:

1. Regular positional arguments


2. Default arguments
3. *args
4. Keyword arguments (**kwargs)

Example
python
Copy code
def example_function(a, b, c=0, *args, **kwargs):
print(a, b, c)
print(args)
print(kwargs)

example_function(1, 2, 3, 4, 5, name="John", age=30)

In this function:

 a and b are positional arguments.


 c is a default argument with a default value of 0.
 *args captures any additional positional arguments.
 **kwargs captures any keyword arguments.

Parameters or Arguments?

The terms parameters and arguments are often used interchangeably in casual conversation,
but they have distinct meanings in programming. Understanding the difference between them is
important for writing clear and accurate code.

Parameters

Parameters are the names listed in a function definition. They act as placeholders for the values
that will be passed into the function when it is called.

 Definition: Parameters are defined in the function's signature.


 Purpose: They specify what kind of data the function expects.
 Scope: Parameters are local to the function; they exist only within the function's body.

Example
python
Copy code
def add(a, b):
return a + b

In this example:

 a and b are parameters of the add function.


Arguments

Arguments are the actual values that you pass to a function when you call it. They are the real
data that the function uses during execution.

 Definition: Arguments are supplied to the function at the time of the function call.
 Purpose: They provide the function with the data it needs to perform its task.
 Scope: Arguments are not part of the function's definition; they are passed to the function
during execution.

Example
python
Copy code
result = add(3, 5)

In this example:

 3 and 5 are arguments passed to the add function.

Putting It All Together

When you define a function, you specify parameters:

python
Copy code
def function_name(param1, param2):
# Function body

When you call the function, you pass arguments:

python
Copy code
function_name(arg1, arg2)

When you call the function, you pass arguments:

python
Copy code
function_name(arg1, arg2)

Detailed Examples

1. Function Definition with Parameters:

python
Copy code
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

 name and age are parameters of the greet function.

Function Call with Arguments:

python
Copy code
greet("Alice", 30)

o "Alice" and 30 are arguments provided to the greet function.

Key Differences

 Parameters are part of the function definition. They define what kind of data the
function

Additional Notes

 Default Parameters: You can specify default values for parameters. These defaults are
used if no arguments are provided for those parameters during the function call.

python
Copy code
def greet(name="Guest", age=25):
print(f"Hello, {name}! You are {age} years old.")

greet() # Uses default values


greet("Bob") # Uses default value for age

Arbitrary Arguments: Functions can accept an arbitrary number of positional arguments (*args) or
keyword arguments (**kwargs).

 def print_all_args(*args):
 for arg in args:
 print(arg)

 print_all_args(1, 2, 3, "hello") # Arguments are 1, 2, 3, "hello"
 python
Copy code
def print_all_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_all_kwargs(name="Alice", age=30) # Keyword arguments are


name="Alice", age=30

Understanding the difference between parameters and arguments helps in writing and
understanding code more effectively, ensuring that function definitions and calls are clear and
precise.
Return Values:
To let a function return a value, use the return statement:
To let a function return a value in Python, you use the return statement. This statement sends the
result of the function back to the caller, allowing you to use the function's output in further
computations or operations. If no return statement is present, the function returns None by
default.
def function_name(parameters):
# Perform operations return value
Example 1: Simple Return
def add(a, b):
return a + b result = add(3, 5)
print(result) # Output: 8

In this example:

 add is a function that takes two parameters, a and b.


 The return statement sends the sum of a and b back to the caller.
 The result is stored in the variable result and then printed.

Example 2: Returning Multiple Values

A function can return multiple values as a tuple. Tuples are a way to group multiple values
together.

A function can return multiple values as a tuple. Tuples are a way to group multiple values
together.

def min_max(numbers):

return min(numbers), max(numbers)

result = min_max([1, 2, 3, 4, 5])

print(result) # Output: (1, 5)

In this example:

 min_max returns two values: the minimum and maximum of the input list.
 These values are returned as a tuple and can be unpacked if needed.
Example 3: Returning a List or Other Data Structures

You can return any data structure, not just primitive types.

python
Copy code
def get_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]

even_numbers = get_even_numbers([1, 2, 3, 4, 5, 6])


print(even_numbers) # Output: [2, 4, 6]

In this example:

 get_even_numbers returns a list of even numbers from the input list.

Example 4: Returning None Explicitly

If you want to explicitly indicate that a function doesn’t return any value, you can use return
None. This is often used to signify that the function performs an action but doesn’t compute or
return a result.

def print_message(message):

print(message)

return None

result = print_message("Hello, World!")

print(result) # Output: None

In this example:

 print_message prints the message but does not return any meaningful value.
 None is explicitly returned, but you could omit the return None as it’s implicit.

Key Points

1. Returning Values: Use the return statement to send a result back from a function.
2. Multiple Values: You can return multiple values as a tuple.
3. Data Structures: Functions can return any type of data structure, such as lists,
dictionaries, or custom objects.
4. Default Return Value: If no return statement is present, the function returns None by
default.

You might also like