Functions in Python (Part-8)

1.Functions in Python

Agenda

  1. Functions in Python
  2. Arguments
  3. *Arbitrary Arguments, args
  4. **Arbitrary Keyword Arguments, kwargs
  5. Return Values from Function

1. Functions in Python

Functions are blocks of code that perform a specific task. They help in organizing code and reusing it.

Example:

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

my_function()
# Output: Hello from a function

2. Arguments

Arguments are values passed to functions. They are specified within the parentheses in the function definition.

Example:

def greet(name):
    print("Hello, " + name)

greet("Alice")
# Output: Hello, Alice

3. Arbitrary Arguments, *args

When the number of arguments is unknown, use *args. It allows the function to receive a variable number of arguments.

Example:

def my_function(*args):
    for arg in args:
        print(arg)

my_function("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry

4. Arbitrary Keyword Arguments, **kwargs

When the number of keyword arguments is unknown, use **kwargs. It allows the function to receive a variable number of keyword arguments.

Example:

def my_function(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

my_function(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York

5. Return Values from Function

Functions can return values using the return statement.

Example:

def add(a, b):
    return a + b

result = add(5, 3)
print(result)
# Output: 8

Functions in Python

  • Definition:
    • A function is a block of code that only runs when it is called. Functions can accept data, known as parameters, and can return data as a result.

Example of Defining and Calling a Function:

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

# Calling the function
my_function()
# Output: Hello from a function

Key Points

  1. Defining a Function:
    • Use the def keyword followed by the function name and parentheses ().
    • Inside the parentheses, you can define parameters if the function needs to accept inputs.
    • The code block within the function is indented.
  2. Calling a Function:
    • To call a function, use the function name followed by parentheses ().
    • If the function has parameters, pass the arguments inside the parentheses.

Function with Parameters

Example:

def greet(name):
    print("Hello, " + name)

# Calling the function with an argument
greet("Alice")
# Output: Hello, Alice

Function Returning a Value

Example:

def add(a, b):
    return a + b

# Calling the function and printing the return value
result = add(5, 3)
print(result)
# Output: 8

Summary

  • Function Definition: Functions are defined using the def keyword followed by the function name and parentheses.
  • Parameters: Functions can accept inputs, known as parameters, which are defined inside the parentheses.
  • Function Call: Functions are called using their name followed by parentheses. If the function has parameters, arguments are passed inside the parentheses.
  • Return Statement: Functions can return a value using the return statement.

Arguments in Python Functions

  • Definition:
    • Information can be passed into functions as arguments. You can add as many arguments as you want, just separate them with a comma. Arguments are often shortened to args in Python documentation.

Examples

  1. Single Argument:
def my_function(fname):
    print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
# Output:
# Emil Refsnes
# Tobias Refsnes
# Linus Refsnes

Multiple Arguments:

def my_function(child3, child2, child1):
    print("The youngest child is " + child3)

my_function(child1="Emil", child2="Tobias", child3="Linus")
# Output:
# The youngest child is Linus

Key Points

  1. Parameters and Arguments:
    • The terms parameter and argument can be used for the same thing: information that is passed into a function.
    • Parameters are variables in the function definition.
    • Arguments are the values passed to the function when it is called.
  2. Number of Arguments:
    • A function must be called with the correct number of arguments.
    • If a function expects two arguments, you must call it with two arguments, not more, and not less.
  3. Key = Value Syntax:
    • You can also send arguments with the key = value syntax.
    • This allows you to assign values to parameters based on their names, rather than their position.
  4. Default Parameter Value:
    • If we call the function without an argument, it uses the default value.

Example of Default Parameter Value

def my_function(country="Norway"):
    print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
# Output:
# I am from Sweden
# I am from India
# I am from Norway

Summary

  • Passing Arguments: Functions can accept any number of arguments, which are separated by commas.
  • Parameters vs. Arguments: Parameters are defined in the function definition; arguments are the actual values passed.
  • Correct Number of Arguments: Functions must be called with the correct number of arguments.
  • Key = Value Syntax: Allows specifying arguments using parameter names.
  • Default Parameter Values: Provide default values for parameters to use when no argument is provided.

Arbitrary Arguments, *args

  • Definition:
    • If you do not know how many arguments will be passed into your function, add a * before the parameter name in the function definition.
    • This way, the function will receive a tuple of arguments and can access the items accordingly.

Example:

def my_function(*kids):
    print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
# Output:
# The youngest child is Linus

Key Points

  1. *Using args:
    • By adding * before the parameter name kids, the function can accept an arbitrary number of arguments.
    • Inside the function, kids is treated as a tuple containing all the arguments passed to the function.
  2. Accessing Items:
    • You can access items in the args tuple using indexing, just like with a regular tuple.
    • In the example, kids[2] accesses the third argument passed to the function.

Example with Loop

Example

def my_function(*args):
    for arg in args:
        print(arg)

my_function("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry

Use Cases for *args

  • Variable Number of Arguments:
    • Use *args when you want to allow the function to handle more arguments than initially specified.
    • This is useful when the number of inputs is unknown or variable.

Example: Sum Function:

def sum_numbers(*numbers):
    total = 0
    for number in numbers:
        total += number
    return total

print(sum_numbers(1, 2, 3, 4, 5))
# Output:
# 15

Summary

  • Arbitrary Arguments: Use *args to allow a function to accept a variable number of non-keyword arguments.
  • Tuple of Arguments: The *args parameter collects arguments into a tuple.
  • Accessing Arguments: Access items in the args tuple using indexing.
  • Flexible Functions: *args makes functions more flexible and adaptable to different numbers of inputs.

Arbitrary Keyword Arguments, **kwargs

  • Definition:
    • If you do not know how many keyword arguments will be passed into your function, add two asterisks ** before the parameter name in the function definition.
    • This way, the function will receive a dictionary of arguments and can access the items accordingly.

Example:

def my_function(**kid):
    print("His last name is " + kid["lname"])

my_function(fname="Tobias", lname="Refsnes")
# Output:
# His last name is Refsnes

Key Points

  1. **Using kwargs:
    • By adding ** before the parameter name kid, the function can accept an arbitrary number of keyword arguments.
    • Inside the function, kid is treated as a dictionary containing all the keyword arguments passed to the function.
  2. Accessing Items:
    • You can access items in the kwargs dictionary using keys, just like with a regular dictionary.
    • In the example, kid["lname"] accesses the value associated with the key lname.

Example with Loop

Example:

def my_function(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

my_function(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York

Use Cases for **kwargs

  • Variable Number of Keyword Arguments:
    • Use **kwargs when you want to allow the function to handle more keyword arguments than initially specified.
    • This is useful when the number of named inputs is unknown or variable.

Example: Student Information:

def print_student_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

print_student_info(name="John", age=18, grade="A")
# Output:
# name: John
# age: 18
# grade: A

Summary

  • Arbitrary Keyword Arguments: Use **kwargs to allow a function to accept a variable number of keyword arguments.
  • Dictionary of Arguments: The **kwargs parameter collects arguments into a dictionary.
  • Accessing Arguments: Access items in the kwargs dictionary using keys.
  • Flexible Functions: **kwargs makes functions more flexible and adaptable to different numbers of named inputs.

Return Values in Python Functions

  • Definition:
    • To let a function return a value, use the return statement.

Example:

def my_function(x):
    return 5 * x

print(my_function(3))  # Output: 15
print(my_function(5))  # Output: 25
print(my_function(9))  # Output: 45

Key Points

  1. Return Statement:
    • The return statement is used to exit a function and return a value to the caller.
    • The value to be returned is specified after the return keyword.
  2. Function Call:
    • When you call a function that returns a value, you can use the returned value in your code.
    • In the example, the function my_function multiplies the input x by 5 and returns the result.
  3. Using Returned Values:
    • You can store the returned value in a variable or directly use it in expressions or other function calls.

Example with Variable

Example:

def add(a, b):
    return a + b

result = add(3, 4)
print(result)  # Output: 7

Example with Conditional Logic

Example:

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

print(is_even(4))  # Output: True
print(is_even(5))  # Output: False

Summary

  • Returning Values: Use the return statement to return a value from a function.
  • Function Call: The returned value can be used in further expressions or stored in variables.
  • Versatility: The return statement allows functions to produce outputs that can be used in various ways, enhancing the versatility and reusability of functions.

2.Recursion Functions in Python

Recursion in Python

  • Definition:
    • Python accepts function recursion, which means a defined function can call itself.
    • This allows a function to be used in complex calculations that can be broken down into simpler sub-problems.

Example: Factorial Calculation

  • Factorial Definition:
    • The factorial of a number 𝑛n is the product of all positive integers less than or equal to 𝑛n.
    • For example, 5!=5×4×3×2×1=1205!=5×4×3×2×1=120.

Example Code:

def factorial(x):
    if x == 1:
        return 1
    else:
        return x * factorial(x - 1)

print(factorial(3))  # Output: 6

Key Points

  1. Base Case:
    • Every recursive function must have a base case that stops the recursion.
    • In the example, the base case is if x == 1: return 1.
  2. Recursive Case:
    • The part of the function where it calls itself with a modified argument.
    • In the example, the recursive case is return x * factorial(x - 1).
  3. Function Call:
    • The function factorial is called with an argument 3.
    • It calls itself with the argument 2, then 1, and so on until the base case is met.

Step-by-Step Execution

  • Step 1: Call factorial(3)
    • Not base case, so returns 3 * factorial(2)
  • Step 2: Call factorial(2)
    • Not base case, so returns 2 * factorial(1)
  • Step 3: Call factorial(1)
    • Base case met, returns 1
  • Step 4: Back to factorial(2)
    • Returns 2 * 1 = 2
  • Step 5: Back to factorial(3)
    • Returns 3 * 2 = 6

Summary

  • Recursion: A function calls itself to solve smaller instances of the same problem.
  • Base Case: Stops the recursion to prevent infinite loops.
  • Recursive Case: Calls the function itself with a modified argument.
  • Use Cases: Suitable for problems that can be broken down into smaller, similar problems (e.g., factorials, Fibonacci sequences, tree traversal).

3.Anonymous Function or Lambda Function in Python

Anonymous or Lambda Functions

  • Definition:
    • A lambda function is a small anonymous function.
    • A lambda function can take any number of arguments but can only have one expression.

Examples of Lambda Functions

Example 1: Single Argument:

x = lambda a: a + 10
print(x(5))  # Output: 15

Example 2: Multiple Arguments:

x = lambda a, b: a * b
print(x(5, 6))  # Output: 30

Using Lambda Functions Inside Another Function

  • Power of Lambda:
    • The power of lambda is better shown when you use them as an anonymous function inside another function.

Example:

def myfunc(n):
    return lambda a: a * n

mydoubler = myfunc(2)
print(mydoubler(11))  # Output: 22

mytripler = myfunc(3)
print(mytripler(11))  # Output: 33

Key Points

  1. Lambda Function Syntax:
    • The syntax is lambda arguments: expression.
    • It can have any number of arguments but only one expression.
    • The expression is evaluated and returned.
  2. Single Expression:
    • Lambda functions can only contain expressions and cannot include statements or multiple expressions.
    • They are useful for simple operations or as short, throwaway functions.
  3. Use Case Inside Functions:
    • Lambdas are often used as anonymous functions passed as arguments to higher-order functions.
    • They are also used to return functions from other functions, as shown in the myfunc example.

Summary

  • Anonymous Functions: Lambdas are small, anonymous functions defined using the lambda keyword.
  • Single Expression: They can take multiple arguments but must contain only one expression.
  • Powerful and Flexible: Lambdas are powerful when used within other functions or as arguments to higher-order functions.
  • Use Cases: Useful for simple operations, short-lived functions, and functional programming constructs.

Related Posts

Package your Python code as Wheel File (Part-20)

Package your Python code as Wheel File If you want to share code with others or create libraries for your code so other can use your code….

Read More

map() function in Python (Part-19)

Using map() Function in Python The map() function in Python is used to apply a function to all the items in an input list. Here are some…

Read More

User Input | input() function |File Handling| open() function in Python (Part-18)

Using input() in Python 3.6 and later When you run this code, it will prompt you to enter a username and then print the entered username. Using…

Read More

Try…Except in Python | Exception handling in Python (part-17)

Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using…

Read More

PIP in Python (Part-16)

What is PIP? PIP is a package manager for Python. It allows you to install and manage additional libraries and dependencies that are not included in the…

Read More

JSON in Python (Part-15)

JSON in Python JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x