0% found this document useful (0 votes)
4 views

Functions_Advanced[1]

The document outlines various types of function arguments in Python, including default, keyword, positional, and arbitrary arguments (*args and **kwargs). It explains the concepts of packing and unpacking arguments, providing examples for each type, and discusses the use of the def keyword for defining functions and methods. Additionally, it covers lambda functions, their syntax, and differences from regular functions, along with practical examples of their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Functions_Advanced[1]

The document outlines various types of function arguments in Python, including default, keyword, positional, and arbitrary arguments (*args and **kwargs). It explains the concepts of packing and unpacking arguments, providing examples for each type, and discusses the use of the def keyword for defining functions and methods. Additionally, it covers lambda functions, their syntax, and differences from regular functions, along with practical examples of their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:

• Default argument

• Keyword arguments (named arguments)

• Positional arguments

• Arbitrary arguments (variable-length arguments *args and **kwargs)

Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:

• *args in Python (Non-Keyword Arguments)

• **kwargs in Python (Keyword Arguments)

Example 1: Variable length non-keywords argument

# Python program to illustrate

# *args for variable number of arguments

def myFun(*argv):

for arg in argv:

print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:

Hello
Welcome
to
GeeksforGeeks

Example 2:

Python program to illustrate *args with a first extra argument.

def fun(arg1, *argv):

print("First argument :", arg1)

for arg in argv:

print("Argument *argv :", arg)

fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output

First argument : Hello


Argument *argv : Welcome

Argument *argv : to

Argument *argv : GeeksforGeeks

Example:

def fun(*args):

for arg in args:

print(arg)

# Calling the function with multiple arguments

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

Output

Python def keyword example with **kwargs

In Python, **kwargs is used to pass a variable number of keyword arguments to a function. The **
syntax collects the keyword arguments into a dictionary, where the keys are the argument names and
the values are the corresponding argument values. This allows the function to accept any number of
named (keyword) arguments.

def fun(**kwargs):

for k, val in kwargs.items():

print(f"{k}: {val}")

# Calling the function with keyword arguments

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

Output

name: Alice

age: 30

city: New York


Explanation:

• **kwargs collects the keyword arguments passed to example_function into a dictionary


kwargs.

• Inside the function, you can iterate over the dictionary and print the key-value pairs.

Pydef myFun1(*argv):

for arg in argv:

print (arg)

def myFun2(**kwargs):

for key, value in kwargs.items():

print ("% s == % s" %(key, value))

# Driver code

print("Result of * args: ")

myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks')

print("\nResult of **kwargs")

myFun2(first ='Geeks', mid ='for', last ='Geeks')

Output:

Result of *args:
Hello
Welcome
to
GeeksforGeeks
Result of **kwargs
mid == for
first == Geeks
last == Geeks

def keyword example with the class

In Python, the def keyword is used to define functions and it can also be used to define methods inside
a class. A method is a function that is associated with an object and is called using the instance of the
class.

When using def inside a class, we can define methods that can access and modify the attributes of the
class and its instances.

class Person:
# Constructor to initialize the person's name and age

def __init__(self, name, age):

self.name = name # Set the name attribute

self.age = age # Set the age attribute

# Method to print a greeting message

def greet(self):

print(f"Name - {self.name} and Age - {self.age}.")

# Create an instance of the Person class

p1 = Person("Alice", 30)

# Call the greet method to display the greeting message

p1.greet()

Output

Name - Alice and Age - 30.

2: Variable length keyword arguments

# Python program to illustrate

# *kwargs for variable number of keyword arguments

def myFun(**kwargs):

for key, value in kwargs.items():

print("%s == %s" % (key, value))

# Driver code

myFun(first='Geeks', mid='for', last='Geeks')

Output:

first == Geeks
mid == for
last == Geeks

Using both *args and **kwargs

We can use both *args and **kwargs in the same function to accept a mix of positional and keyword
arguments.
Example:

def fun(*args, **kwargs):

print("Positional arguments:", args)

print("Keyword arguments:", kwargs)

fun(1, 2, 3, a=4, b=5)

Output

Positional arguments: (1, 2, 3)

Keyword arguments: {'a': 4, 'b': 5}

Packing and Unpacking Arguments in Python

Python provides the concept of packing and unpacking arguments, which allows us to handle
variable-length arguments efficiently. This feature is useful when we don’t know beforehand how
many arguments will be passed to a function.

Packing Arguments

Packing allows multiple values to be combined into a single parameter using * (for tuples/lists) and **
(for dictionaries).

• *args (Non-keyword arguments): Packs multiple positional arguments into a tuple.

• **kwargs (Keyword arguments): Packs multiple keyword arguments into a dictionary.

1. Packing with *args

The * operator allows us to pass multiple arguments to a function and pack them into a tuple.

Example Code:

def sample(*args):

print("Packed arguments:", args)

sample(1, 2, 3, 4, "geeks for geeks")

Output

Packed arguments: (1, 2, 3, 4, 'geeks for geeks')

2. Packing with **kwargs

** operator is used to collect multiple keyword arguments into a dictionary.

Code

def sample(**kwargs):

print("Packed keyword arguments:", kwargs)


sample(name="Anaya", age=25, country="India")

Output

Packed keyword arguments: {'name': 'Anaya', 'age': 25, 'country': 'India'}

Unpacking Arguments

Unpacking allows values from an iterable (list, tuple, or dictionary) to be passed as separate
arguments to a function.

1. Unpacking a List/Tuple with *

We use * to unpack elements from a list/tuple.

Example

def addition(a, b, c):

return a + b + c

num = (1, 5, 10)

result = addition(*num)

print("Sum:", result)

Output

Sum: 16

Explanation: *numbers unpacks numbers into a, b, c.

2. Unpacking a Dictionary with **

We use ** to unpack key-value pairs from a dictionary.

Example

def info(name, age, country):

print(f"Name: {name}, Age: {age}, Country: {country}")

data = {"name": "geeks for geeks", "age": 30, "country": "India"}

info(**data)

Output

Name: geeks for geeks, Age: 30, Country: India

Explanation: **data unpack dictionary values and assign them to parameters.


Packing and Unpacking Together

We can use Packing and Unpacking in same function.

Example

def together(*args, **kwargs):

print("Positional:", args)

print("Keyword arguments:", kwargs)

together(1, 2, 3, name="geeks for geeks", age=30)

Output

Positional: (1, 2, 3)

Keyword arguments: {'name': 'geeks for geeks', 'age': 30}

Explanation:

• *args collects (1, 2, 3) as a tuple.

• **kwargs collects name="geeks for geeks" and age=30 into a dictionary.

Difference between Packing and Unpacking

Features Packing Unpacking

Collects multiple values into a Extracts values from a collection (tuple,


single variable (tuple, list, or list, or dictionary) into individual
Definition dictionary). variables.

* (for tuples/lists), ** (for


* (for lists/tuples), ** (for dictionaries).
Operator Used dictionaries).

Allows functions to accept a Allows passing values dynamically to


Purpose variable number of arguments. functions or variables.

Combine multiple values into a Extracts multiple values from a single


Data Structure single entity (tuple or dictionary). entity into separate variables.
Features Packing Unpacking

def func(*args): (packs multiple


func(*list_var) (unpacks elements from a
positional arguments into a tuple)
list/tuple)
Example in def func(**kwargs): (packs multiple
func(**dict_var) (unpacks key-value
function keyword arguments into a
pairs from a dictionary)
definition dictionary)

Example inf func(1, 2, 3, 4) → Packs (1, 2, 3, func(*[1, 2, 3, 4]) → Unpacks [1, 2, 3,


unction call 4) into args. 4] as separate arguments.

Storage Tuple (*args) or Dictionary Individual variables or function


Format (**kwargs). arguments.

Docstring

The first string after the function is called the Document string or Docstring in short. This is used to
describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.

The below syntax can be used to print out the docstring of a function.

Syntax: print(function_name.__doc__)

Example: Adding Docstring to the function

# A simple Python function to check

# whether x is even or odd

def evenOdd(x):

"""Function to check if the number is even or odd"""

if (x % 2 == 0):

print("even")

else:

print("odd")

# Driver code to call the function

print(evenOdd.__doc__)

Output:

Function to check if the number is even or odd


Frequently Asked Questions (FQAs)

How to use def in Python?

The def keyword in Python is used to define functions. We start with def, followed by the function
name and any parameters in parentheses. The function body, indented below, contains the code to be
executed. Optionally, we can use the return statement to send a value back when the function is called.
This structure allows us to create reusable and organized code blocks.

What is the purpose of the def keyword in Python?

The def keyword in Python is used to define functions. It allows you to create reusable blocks of code
with a specific name, making your code modular, organized and easier to maintain.

Can a Python function have multiple return statements?

Yes, a Python function can have multiple return statements. However, once a return statement is
executed, the function exits and subsequent code is not executed. Each return statement can provide
different outcomes based on conditions within the function.

What is def __init__(self) in Python?

def __init__(self) is the constructor method in Python, used in classes. It initializes the object’s
attributes when an instance of the class is created.

Example:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

person = Person("Alice", 30)

print(person.name) # Output: Alice

print(person.age) # Output: 30

In this example, __init__ initializes the name and age attributes of the Person class.

Is *args a list or tuple in Python?

*args collects additional positional arguments into a tuple, not a list. The arguments are accessible
using tuple indexing and iteration.

def example_function(*args):
print(type(args)) # <class 'tuple'>
example_function(1, 2, 3)

Why use *args instead of a list?


*args is used when you want to pass a variable number of arguments to a function without explicitly
specifying each argument in a list. It allows for flexibility and simplicity when defining functions that
may take an unknown number of arguments.

def sum_values(*args):
total = sum(args)
return total
result = sum_values(1, 2, 3, 4, 5)
print(result) # Output: 15

Python Function within Functions

A function that is defined inside another function is known as the inner function or nested function.
Nested functions can access variables of the enclosing scope. Inner functions are used so that they can
be protected from everything happening outside the function.

# Python program to demonstrate accessing of variables of nested functions

def f1():

s = 'I love GeeksforGeeks'

def f2():

print(s)

f2()

# Driver's code

f1()

Output:

I love GeeksforGeeks

What are the 4 types of Functions in Python?

The main types of functions in Python are:

• Built-in function

• User-defined function

• Lambda functions [Anonymous Functions in Python]

• Recursive functions

Anonymous Functions in Python

In Python, an anonymous function means that a function is without a name. As we already know the
def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.

# Python code to illustrate the cube of a number using lambda function


def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))

print(cube_v2(7))

Output:

343
343

s1 = 'GeeksforGeeks'

s2 = lambda func: func.upper()

print(s2(s1))

Output

GEEKSFORGEEKS

Python Lambda Function Syntax

Syntax: lambda arguments : expression

• lambda: The keyword to define the function.

• arguments: A comma-separated list of input parameters (like in a regular function).

• expression: A single expression that is evaluated and returned.

Let’s see some of the practical uses of the Python lambda function.

lambda with Condition Checking

A lambda function can include conditions using if statements.

Example:

# Example: Check if a number is positive, negative, or zero

n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"

print(n(5))

print(n(-3))

print(n(0))

Output

Positive

Negative

Zero
Difference Between lambda and def Keyword

lambda is concise but less powerful than def when handling complex logic. Let’s take a look at short
comparison between the two:

Feature lambda Function Regular Function (def)

Definition Single expression with lambda. Multiple lines of code.

Name Anonymous (or named if assigned). Must have a name.

Statements Single expression only. Can include multiple statements.

Documentation Cannot have a docstring. Can include docstrings.

Reusability Best for short, temporary functions. Better for reusable and complex logic.

Example:

Using lambda

sq = lambda x: x ** 2

print(sq(3))

# Using def

def sqdef(x):

return x ** 2

print(sqdef(3))

Output

As we can see in the above example, both the sq() function and sqdef() function behave the same and
as intended.

Lambda with List Comprehension

Combining lambda with list comprehensions enables us to apply transformations to data in a concise
way.

Example:
li = [lambda arg=x: arg * 10 for x in range(1, 5)]

for i in li:

print(i())

Output

10

20

30

40

Explanation:

• The lambda function squares each element.

• The list comprehension iterates through li and applies the lambda to each element.

• This is ideal for applying transformations to datasets in data preprocessing or manipulation


tasks.

Lambda with if-else

lambda functions can incorporate conditional logic directly, allowing us to handle simple decision
making within the function.

Example:

# Example: Check if a number is even or odd

check = lambda x: "Even" if x % 2 == 0 else "Odd"

print(check(4))

print(check(7))

Output

Even

Odd

Explanation:

• The lambda checks if a number is divisible by 2 (x % 2 == 0).

• Returns “Even” for true and “Odd” otherwise.

• This approach is useful for labeling or categorizing values based on simple conditions.

Lambda with Multiple Statements


Lambda functions do not allow multiple statements, however, we can create two lambda functions and
then call the other lambda function as a parameter to the first function.

Example:

# Example: Perform addition and multiplication in a single line

calc = lambda x, y: (x + y, x * y)

res = calc(3, 4)

print(res)

Output

(7, 12)

Explanation:

• The lambda function performs both addition and multiplication and returns a tuple with both
results.

• This is useful for scenarios where multiple calculations need to be performed and returned
together.

Lambda functions can be used along with built-in functions like filter(), map() and reduce().

Using lambda with filter()

The filter() function in Python takes in a function and a list as arguments. This offers an elegant way
to filter out all the elements of a sequence “sequence”, for which the function returns True.

The filter() method filters the given sequence with the help of a function that tests each element in the
sequence to be true or not. Let’s see a simple example of filter() function in python:

Example:

# Example: Filter even numbers from a list

n = [1, 2, 3, 4, 5, 6]

even = filter(lambda x: x % 2 == 0, n)

print(list(even))

Output

[2, 4, 6]

Explanation:

• The lambda function checks if a number is even (x % 2 == 0).

• filter() applies this condition to each element in nums.


Example Usage of filter()

# Function to check if a number is even

def even(n):

return n % 2 == 0

a = [1, 2, 3, 4, 5, 6]

b = filter(even, a)

# Convert filter object to a list

print(list(b))

Output

[2, 4, 6]

Explanation:

• Function: even function checks if a number is divisible by 2.

• Filter: The filter() applies this function to each item in numbers.

• Result: A new iterable containing only even numbers is returned.

Let’s explore filter() in detail:

Python filter() Syntax

The filter() method in Python has the following syntax:

Syntax: filter(function, sequence)

• function: A function that defines the condition to filter the elements. This function should
return True for items you want to keep and False for those you want to exclude.

• iterable: The iterable you want to filter (e.g., list, tuple, set).

The result is a filter object, which can be converted into a list, tuple or another iterable type.

Let us see a few examples of the filter() function in Python.

Using filter() with lambda

For concise conditions, we can use a lambda function instead of defining a named function.

a = [1, 2, 3, 4, 5, 6]

b = filter(lambda x: x % 2 == 0, a)
print(list(b))

Output

[2, 4, 6]

Here, the lambda function replaces even and directly defines the condition x % 2 == 0 inline.

Combining filter() with Other Functions

We can combine filter() with other Python functions like map() or use it in a pipeline to process data
efficiently.

Example: Filtering and Transforming Data

a = [1, 2, 3, 4, 5, 6]

# First, filter even numbers

b = filter(lambda x: x % 2 == 0, a)

# Then, double the filtered numbers

c = map(lambda x: x * 2, b)

print(list(c))

Output

[4, 8, 12]

Explanation:

• The filter() function extracts even numbers from numbers.

• The map() function doubles each filtered number.

• The combination simplifies complex data pipelines.

filter() in python – FAQs

What does the filter() function do?

The filter() function in Python filters elements from an iterable (like a list) based on a function (or
None for truthy values). It returns an iterator that yields those elements for which the function returns
True.

How does reduce() and filter() work in Python?

• filter(): Filters elements from an iterable based on a function.


• reduce(): Applies a function to the items of an iterable, cumulatively, from left to right, so as
to reduce the iterable to a single value.

Both functions are part of Python’s functools module (Python 3.x) and can be used together to filter
and then reduce data if needed.

How to filter a list in Python?

To filter a list in Python, you can use a list comprehension or the filter() function along with a lambda
function or a defined function.

Using list comprehension:

# Example using list comprehension


a= [1, 2, 3, 4, 5, 6, 7, 8, 9]
b= [num for num in a if num % 2 == 0]
print(b) # Output: [2, 4, 6, 8]

Using lambda with map()

The map() function is used to apply a given function to every item of an iterable, such as
a list or tuple, and returns a map object (which is an iterator).

Let’s start with a simple example of using map() to convert a list of strings into a list of integers.

s = ['1', '2', '3', '4']

res = map(int, s)

print(list(res))

Output

[1, 2, 3, 4]

Explanation: Here, we used the built-in int function to convert each string in the list s into an integer.
The map() function takes care of applying int() to every element

Syntax of the map() function

The syntax for the map() function is as follows:

map(function, iterable)

Parameter:

• function: The function we want to apply to every element of the iterable.

• iterable: The iterable whose elements we want to process.

Note: We can also pass multiple iterables if our function accepts multiple arguments.

Converting map object to a list

By default, the map() function returns a map object, which is an iterator. In many cases, we will
need to convert this iterator to a list to work with the results directly.
Example: Let’s see how to double each elements of the given list.

a = [1, 2, 3, 4]

# Using custom function in "function" parameter

# This function is simply doubles the provided number

def double(val):

return val*2

res = list(map(double, a))

print(res)

Output

[2, 4, 6, 8]

Explanation:

• The map() function returned an iterator, which we then converted into a list using list(). This
is a common practice when working with map()

• We used a custom function to double each value in the list a. The result was mapped and
converted into a list for easy display.

map() with lambda

We can use a lambda function instead of a custom function with map() to make the code shorter and
easier. Let’s see how to improve the above code for better readability.

a = [1, 2, 3, 4]

# Using lambda function in "function" parameter

# to double each number in the list

res = list(map(lambda x: x * 2, a))

print(res)

Output

[2, 4, 6, 8]

Explanation: We used lambda x: x * 2 to double each value in the list a. The result was mapped and
converted into a list for easy display.

Using map() with multiple iterables


We can use map() with multiple iterables if the function we are applying takes more than one
argument.

Example: In this example, map() takes two iterables (a and b) and applies the lambda function to add
corresponding elements from both lists.

a = [1, 2, 3]

b = [4, 5, 6]

res = map(lambda x, y: x + y, a, b)

print(list(res))

Output

[5, 7, 9]

Examples of map() function

Converting to uppercase

This example shows how we can use map() to convert a list of strings to uppercase.

fruits = ['apple', 'banana', 'cherry']

res = map(str.upper, fruits)

print(list(res))

Output

['APPLE', 'BANANA', 'CHERRY']

Explanation: The str.upper method is applied to each element in the list fruits using map(). The
result is a list of uppercase versions of each fruit name.

Extracting first character from strings

In this example, we use map() to extract the first character from each string in a list.

words = ['apple', 'banana', 'cherry']

res = map(lambda s: s[0], words)

print(list(res))

Output

['a', 'b', 'c']

Explanation: The lambda function s: s[0] extracts the first character from each string in the list
words. map() applies this lambda function to every element, resulting in a list of the first characters of
each word.

Removing whitespaces from strings


In this example, We can use map() to remove leading and trailing whitespaces from each string in a
list.

s = [' hello ', ' world ', ' python ']

res = map(str.strip, s)

print(list(res))

Output

['hello', 'world', 'python']

Explanation: The str.strip method removes leading and trailing whitespaces from each string in the
list strings. The map() function applies str.strip to each element and returning a list of trimmed
strings.

Calculate fahrenheit from celsius

In this example, we use map() to convert a list of temperatures from Celsius to Fahrenheit.

celsius = [0, 20, 37, 100]

fahrenheit = map(lambda c: (c * 9/5) + 32, celsius)

print(list(fahrenheit))

Output

[32.0, 68.0, 98.6, 212.0]

The map() function in Python takes in a function and a list as an argument. The function is called with
a lambda function and a new list is returned which contains all the lambda-modified items returned by
that function for each item.

Example:

# Example: Double each number in a list

a = [1, 2, 3, 4]

b = map(lambda x: x * 2, a)

print(list(b))

Output

[2, 4, 6, 8]

Explanation:

• The lambda function doubles each number.

• map() iterates through a and applies the transformation.

Using lambda with reduce()


The reduce() function in Python takes in a function and a list as an argument. The function is called
with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive
operation over the pairs of the iterable. The reduce() function belongs to the functools module.

Example:

from functools import reduce

# Example: Find the product of all numbers in a list

a = [1, 2, 3, 4]

b = reduce(lambda x, y: x * y, a)

print(b)

Output

24

Explanation:

• The lambda multiplies two numbers at a time.

• reduce() applies this operation across the list.

reduce() in Python

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all
of the list elements mentioned in the sequence passed along. This function is defined in “functools”
module.

Basic Example:

Let’s start with a simple example where we sum up all numbers in a list.

from functools import reduce

# Function to add two numbers

def add(x, y):

return x + y

a = [1, 2, 3, 4, 5]

res = reduce(add, a)

print(res) # Output: 15
Output

15

Explanation:

• The reduce() function applies add() cumulatively to the elements in numbers. First, 1 + 2 = 3.
Then, 3 + 3 = 6. And so on, until all numbers are processed.

• The final result is 15.

Let’s understand reduce function in detail:

Syntax of reduce()

functools.reduce(function, iterable[, initializer])

• function: A function that takes two arguments and performs an operation on them.

• iterable: An iterable whose elements are processed by the function.

• initializer (optional): A starting value for the operation. If provided, it is placed before the
first element in the iterable.

The reduce() function is part of the functools module, so you need to import it before use.

Using reduce() with lambda

When paired with a lambda function, reduce() becomes a concise and powerful tool for aggregation
tasks like summing, multiplying or finding the maximum value.

from functools import reduce

# Summing numbers with reduce and lambda

a = [1, 2, 3, 4, 5]

res = reduce(lambda x, y: x + y, a)

print(res)

Output

15

Explanation:

• The lambda function takes two arguments (x and y) and returns their sum.

• reduce() starts by applying the function to the first two elements: 1 + 2 = 3.

• The result (3) is then used with the next element: 3 + 3 = 6, and so on.

• The process continues until all elements are processed, yielding 15.

Using reduce() with operator functions


reduce() can also be combined with operator functions to achieve the similar functionality as with
lambda functions and makes the code more readable.

import functools

# importing operator for operator functions

import operator

# initializing list

a = [1, 3, 5, 6, 2]

# using reduce with add to compute sum of list

print(functools.reduce(operator.add, a))

# using reduce with mul to compute product

print(functools.reduce(operator.mul, a))

# using reduce with add to concatenate string

print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))

Output

17

180

geeksforgeeks

Explanation:

• operator.add and operator.mul function are predefined operators.

• reduce() applies the add function cumulatively to elements in the list.

• The operation works similarly to the lambda example but the code is cleaner and more
readable.

reduce() in Python – FAQs

What is the reduce method in a list?

The reduce function is used to apply a function of two arguments cumulatively to the items of a list (or
any iterable), from left to right, so as to reduce the iterable to a single value. It’s not a method of the
list but a function in the functools module.
What is the return value of reduce() function?

The return value of the reduce() function is a single value, which is the result of the cumulative
application of the provided function to the elements of the iterable.

Which module should we import to use the reduce() function?

To use the reduce() function, you need to import it from the functools module.

How to import the reduce function from the functools module?

You can import the reduce function from the functools module using the following import statement:

from functools import reduce

Recursive Functions in Python

Recursion in Python refers to when a function calls itself. There are many instances when you have to
build a recursive function to solve Mathematical and Recursive Problems.

Using a recursive function should be done with caution, as a recursive function can become like a
non-terminating loop. It is better to check your exit statement while creating a recursive function.

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

print(factorial(4))

Output

24

Here we have created a recursive function to calculate the factorial of the number. You can see the end
statement for this function is when n is equal to 0.

Characteristics of First-Class Functions

• Assigned to Variables: We can assign functions to variables.

• Passed as Arguments: We can pass functions as arguments to other functions.

• Returned from Functions: Functions can return other functions.

• Stored in Data Structures: Functions can be stored in data structures such as lists,
dictionaries, etc.

Assigning Functions to Variables / How to set a function as a variable?/ How to store a function
in a variable in Python?

We can assign a function to a variable and use the variable to call the function.
Example:

def msg(name):

return f"Hello, {name}!"

# Assigning the function to a variable

f = msg

# Calling the function using the variable

print(f("Anurag"))

Output

Hello, Anurag!

Explanation:

• function greet is assigned to the variable f.

• f is then used to call the function, demonstrating that functions can be treated like any other
variable.

• # defined function
• x = 123

• def sum():
• x = 98
• print(x)
• print(globals()['x'])


• # drivercode
• print(x)

• # assigning function
• z = sum

• # invoke function
• z()
• z()
• Output:
• 123
98
123
98
123
• Example 2: parameterized function
• # function defined
• def even_num(a):
• if a % 2 == 0:
• print("even number")
• else:
• print("odd number")


• # drivercode
• # assigning function
• z = even_num

• # invoke function with argument
• z(67)
• z(10)
• z(7)
• Output:
• odd number
even number
odd number

Passing Functions as Arguments

Functions can be passed as arguments to other functions, enabling higher-order functions.

Example:

def msg(name):

return f"Hello, {name}!"

def fun1(fun2, name):

return fun2(name)

# Passing the greet function as an argument

print(fun1(msg, "Bob"))

Output

Hello, Bob!

Explanation:

• The fun1 function takes another function fun2 and a name as arguments.

• The msg function is passed to fun1, which then calls greet with the given name.

Returning Functions from Other Functions

A function can return another function, allowing for the creation of function factories.
Example:

def fun1(msg):

def fun2():

return f"Message: {msg}"

return fun2

# Getting the inner function

func = fun1("Hello, World!")

print(func())

Output

Message: Hello, World!

Explanation:

• The fun1 defines an fun2 and returns it.

• func stores the returned fun2, which can then be called later.

Storing Functions in Data Structures

Functions can be stored in data structures like lists or dictionaries.

Example:

def add(x, y):

return x + y

def subtract(x, y):

return x - y

# Storing functions in a dictionary

d={

"add": add,

"subtract": subtract

# Calling functions from the dictionary


print(d["add"](5, 3))

print(d["subtract"](5, 3))

Output

Explanation:

• Functions add and subtract are stored in a dictionary operations.

• Functions are accessed and called from the dictionary using their respective keys.

What are the disadvantages of user-defined functions in Python?

• Performance overhead: User-defined functions may introduce a slight performance overhead


compared to inbuilt functions, as they add an extra layer of function calls.

• Potential for errors: Errors in logic or implementation can lead to bugs and unexpected
behavior.

• Maintenance: Custom functions require maintenance and documentation, especially in larger


projects.

• Redundancy: If not designed properly, user-defined functions can lead to redundant or


duplicated code.

What is the difference between user-defined and predefined functions?

def greet(name):
return f"Hello, {name}!"

• User-defined functions: Created by the programmer to perform specific tasks, using the def
keyword. Example:

• Predefined (inbuilt) functions: Provided by Python, ready to use, and do not require
definition. Example:

length = len("example") # len is a predefined function

Python | How to get function name ?

Method 1: Get Function Name in Python using function.__name__

This function has been introduced in Python 3 in Python3.

• Python3

# initializing function

def GFG():
return "You just called for success !!"

# printing function name

# using function.__name__

print("The name of function is : " + GFG.__name__)

Output :

The name of function is : GFG

Method 2: Get Function Name in Python using function.func_name

By using a simple function property function, func_name, one can get the name of the function and
hence can be quite handy for the Testing purpose and also for documentation at times. The drawback
is that this works just for Python2.

• Python

# initializing function

def GFG():

return "You just called for success !!"

# printing function name

# using function.func_name

print("The name of function is : " + GFG.func_name)

Output :

The name of function is : GFG

Method 3: Get Function Name in Python using __qualname__ attribute

The __qualname__ gives more complete information than __name__ and therefore can be more
helpful in debugging. To extract the name from any object or class, you can also use its __qualname__
attribute.

• Python3

def Geekforgeeks():
pass

class Geekforgeeks(object):

def my_method(self):

pass

# "my_function"

print(Geekforgeeks.__qualname__)

# "My_Class.my_method"

print(Geekforgeeks.my_method.__qualname__)

Output :

Geekforgeeks

Geekforgeeks.my_method

Method 4: Get Function Name in Python using the inspect module

This code imports the inspect module and defines a function get_function_name() that returns the
name of the function. The function uses the inspect.currentframe() function to get the frame object of
the current function, and then returns the co_name attribute of the f_code attribute of the frame object,
which is the name of the function.

The inspect.currentframe() function returns a frame object for the frame of the caller. The frame
object is an instance of the FrameInfo class, which has several attributes that provide information
about the frame, such as the f_code attribute, which is the code object for the function, and the
co_name attribute, which is the name of the function.

Finally, the code prints the name of the function using the get_function_name() function.

• Python3

import inspect

# initializing function

def get_function_name():

# get the frame object of the function

frame = inspect.currentframe()

return frame.f_code.co_name

# printing function name


print("The name of function is : " +get_function_name()) # test_function

#This code is contributed by Edula Vinay Kumar Reddy

Output

The name of function is : get_function_name

This approach has a time complexity of O(1) and an auxiliary space of O(1).

Defining a Python function at runtime

In Python,we can define a python function at runtime execute with the help of FunctionType(). First
we import types module then perform compile() function and pass parameter exec and after that with
the help FunctionType() define the function at runtime.

Example 1: Function to print GEEKSFORGEEKS.

• Python3

# importing the module

from types import FunctionType

# functttion during run-time

f_code = compile('def gfg(): return "GEEKSFORGEEKS"', "<string>", "exec")

f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")

# calling the function

print(f_func())

Output:

GEEKSFORGEEKS

Example 2: Function to add 2 numbers.

• Python3

# importing the module

from types import FunctionType

# function at run-time
f_code = compile('def gfg(a, b): return(a + b) ', "<int>", "exec")

f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")

val1 = 3999

val2 =4999

# calliong the function

print(f_func(val1, val2))

Output:

8998

Explicitly define datatype in a Python function

Last Updated : 10 Jul, 2024

Unlike other languages Java, C++, etc. Python is a strongly, dynamically-typed language in which we
don’t have to specify the data type of the function’s return value and its arguments. It relates types
with values instead of names. The only way to specify data of specific types is by providing explicit
datatypes while calling the functions.

Example 1: We have a function to add 2 elements.

# function definition

def add(num1, num2):

print("Datatype of num1 is ", type(num1))

print("Datatype of num2 is ", type(num2))

return num1 + num2

# calling the function without

# explicitly declaring the datatypes

print(add(2, 3))

# calling the function by explicitly


# defining the datatypes as float

print(add(float(2), float(3)))

Output:

Datatype of num1 is <class 'int'>


Datatype of num2 is <class 'int'>
5
Datatype of num1 is <class 'float'>
Datatype of num2 is <class 'float'>
5.0

Example 2: We have a function for string concatenation

# function definition

def concatenate(num1, num2):

print("Datatype of num1 is ", type(num1))

print("Datatype of num2 is ", type(num2))

return num1 + num2

# calling the function without

# explicitly declaring the datatypes

print(concatenate(111, 100))

10

11

# calling the function by explicitly

12
# defining the datatypes as string

13

print(concatenate(str(111), str(100)))

211

Output:

Datatype of num1 is <class 'int'>


Datatype of num2 is <class 'int'>
211
Datatype of num1 is <class 'str'>
Datatype of num2 is <class 'str'>
111100

Explicitly define datatype in a Python function – FAQs

How to explicitly define data types in Python function parameters?

To define data types explicitly in function parameters, you use type annotations. Here’s an example of
how to annotate a function:

def add_numbers(a: int, b: int) -> int:


return a + b

In this example, a and b are expected to be integers, and the function is expected to return an integer.

Can we enforce data type checking in Python functions?

Python itself does not enforce data type checking at runtime based solely on type annotations.
However, you can enforce data type checking using custom checks within the function, or more
commonly, through third-party libraries like mypy, which perform static type checking.

If you want to enforce types at runtime, you might manually assert types like this:

def add_numbers(a: int, b: int) -> int:


assert isinstance(a, int) and isinstance(b, int), "Both arguments must be integers"
return a + b

What is the syntax for specifying data types in function definitions?

The syntax for specifying data types in function definitions involves adding a colon : followed by the
data type after each parameter, and an arrow -> followed by the data type after the parentheses to
indicate the return type. Here is a general template:

from typing import List, Optional

def process_items(items: List[str], separator: Optional[str] = None) -> str:


if separator is None:
separator = ', '
return separator.join(items)

print(process_items(['apple', 'banana', 'cherry'])) # Outputs: apple, banana, cherry


Accessing Python Function Variable Outside the Function

In Python, variables defined within a function have local scope by default. But to Access function
variables outside the function usually requires the use of the global keyword, but can we do it without
using Global. In this article, we will see how to access a function variable outside the function without
using "Global".

Accessing Function Variable Outside the Function in Python

Below, are the ways to access a function variable outside the function without using Global in Python.

• Return the Variable

• Using Function Parameter

• Using a Class

• Using a Decorator

Access Function Variable Outside the Function by Returning the Variable

In this approach, the function returns the value of the variable, allowing access to the variable outside
the function by assigning the result to a variable. The function get_variable() defines a variable var
with the value 42 and returns it outside the function without using Global.

def get_variable():

var = 42

return var

# Accessing the function variable outside the function

result = get_variable()

print(result)

Output

42

Python Access Variable Outside the Function Using Function Parameter

In this approach the function takes a variable as a parameter, modifies it, and returns the modified
value. The original variable is passed to the function. The function modify_variable(var) takes a
variable as a parameter, increments its value by 10, and returns the modified value. By passing an
original variable to the function and assigning the result to another variable (modified_var), the
modified value (15) is accessible and printed outside the function.

def modify_variable(var):

var += 10
return var

# Define a variable outside the function

original_var = 5

# Passing the variable to the function

modified_var = modify_variable(original_var)

print(modified_var)

Output

15

Accessing Function Variables Outside Scope Using a Class

In this approach we create an instance of the class, the variable becomes an attribute of that instance,
making it accessible without the need for the global keyword. In the example, a
class VariableHolder is defined with an __init__ method initializing the variable to 42.

class VariableHolder:

def __init__(self):

self.var = 42

# Creating an instance of the class

holder = VariableHolder()

# Accessing the variable through the instance

print(holder.var)

Output

42

Access a Function Variable Outside the Function Using a Decorator

In this approach, a decorator function (store_variable) is defined, which takes another function as
an argument. The decorator wraps the original function, storing its result as an attribute of the
wrapper function. When the decorated function is called, it not only returns the result but also makes
the result accessible through the attribute. In the example, the @store_variable decorator is applied
to the get_variable function, and the variable's value can be accessed using the
attribute get_variable.variable.
def store_variable(func):

def wrapper(*args, **kwargs):

result = func(*args, **kwargs)

wrapper.variable = result

return result

return wrapper

@store_variable

def get_variable():

return 42

# Accessing the variable through the decorated function

get_variable()

print(get_variable.variable)

Output

42

Accessing Python Function Variable Outside the Function - FAQs

How to access a variable outside a function in Python?

To access a variable outside a function, you can declare it as a global variable. For example:

# Global variable
x = 10

def print_x():
print(x)

print_x() # Output: 10

In this example, x is a global variable and can be accessed inside the print_x function.

How to access another function variable in Python?

To access a variable from another function, pass it as an argument. For example:

def func1():
y=5
return y
def func2(value):
print(value)

variable = func1()
func2(variable) # Output: 5

In this example, func1 returns the variable y, and func2 takes it as an argument.

Can you access a variable defined inside a function outside the function?

No, you cannot directly access a variable defined inside a function from outside that function. Instead,
you can return it. For example:

def func():
z = 20
return z

result = func()
print(result) # Output: 20

In this example, z is returned by func and accessed outside the function.

How to get a value out of a function in Python?

Use the return statement to get a value out of a function. For example:

def add(a, b):


return a + b

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

In this example, the add function returns the sum of a and b.

How to get something out of a function in Python?

Use the return statement to get something out of a function. For example:

def get_info():
name = "Alice"
age = 30
return name, age

name, age = get_info()


print(name, age) # Output: Alice 30

How to find the number of arguments in a Python function?

In this article, we are going to see how to count the number of arguments of a function in Python. We
will use the special syntax called *args that is used in the function definition of python. Syntax *args
allow us to pass a variable number of arguments to a function. We will use len() function or method in
*args in order to count the number of arguments of the function in python.
Example 1:
def no_of_argu(*args):

# using len() method in args to count

return(len(args))

Passing function as an argument in Python

Last Updated : 14 Aug, 2024

A function can take multiple arguments, these arguments can be objects, variables(of same or different
data types) and functions. Python functions are

first class

objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the
function. It takes the function object referenced by shout and creates a second name pointing to it,
yell.

# Python program to illustrate functions

# can be treated as objects

def shout(text):

return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))

Output:

HELLO
HELLO

Higher Order Functions

Because functions are objects we can pass them as arguments to other functions. Functions that can
accept other functions as arguments are also called

higher-order functions

. In the example below, a function greet is created which takes a function as an argument.
# Python program to illustrate functions

# can be passed as arguments to other functions

def shout(text):

return text.upper()

def whisper(text):

return text.lower()

def greet(func):

# storing the function in a variable

greeting = func("Hi, I am created by a function passed as an argument.")

print(greeting)

greet(shout)

greet(whisper)

Output

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.


hi, i am created by a function passed as an argument.

Wrapper function

Wrapper function or decorator allows us to wrap another function in order to extend the behavior of
the wrapped function, without permanently modifying it. In Decorators, functions are taken as the
argument into another function and then called inside the wrapper function. To know more about
decorator

click here

. Below is the example of a simple decorator.

# defining a decorator

def hello_decorator(func):

#inner1 is a Wrapper function in which the argument is called

def inner1():

print("Hello, this is before function execution")

func()

print("This is after function execution")


return inner1

def function_to_be_used():

print("This is inside the function !!")

function_to_be_used = hello_decorator(function_to_be_used)

function_to_be_used()

Output:

Hello, this is before function execution


This is inside the function !!
This is after function execution

Passing function as an argument in Python – FAQs

Can I Pass Functions as Arguments in Python?

Yes, in Python, functions are first-class objects. This means they can be passed as arguments to other
functions, returned as values from other functions, and assigned to variables.

How Do You Pass a Function as an Argument?

To pass a function as an argument, simply refer to the function by its name without parentheses.
Here’s a simple example:

def greet(name):
return f"Hello, {name}!"

def farewell(name):
return f"Goodbye, {name}!"

def process_user(callback, name):


print(callback(name))

# Passing functions as arguments


process_user(greet, "Alice")
process_user(farewell, "Bob")

This example demonstrates how a function can be passed as an argument (callback) to another
function (process_user) and then executed within that function.

How Do You Pass a Function as an Argument in Python Decorator?

A decorator in Python is a function that takes another function and extends its behavior without
explicitly modifying it. Here’s how to create a decorator that takes a function as an argument:

def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")

# Calling the decorated function


say_hello()

In this example, say_hello() is passed to my_decorator() as the func argument. The wrapper function
adds behavior before and after the call to say_hello().

How Do You Declare a Function Passing Argument?

To declare a function that can pass arguments, you define it using the def keyword followed by the
function name and parentheses containing the arguments:

def multiply(x, y):


return x * y

# Using the function


result = multiply(5, 3)
print(result) # Output: 15

This function multiply takes two arguments, x and y, and returns their product.

How Many Types of Arguments Are There in Python?

Python supports several types of arguments:

1. Positional Arguments: These are arguments that need to be passed in the correct positional
order.

2. Keyword Arguments: Arguments that are passed to functions using the name of the
parameter, regardless of their position.

3. Default Arguments: Parameters that assume a default value if a value is not provided in the
function call.

4. Variable-length Arguments:

• Arbitrary Positional Arguments (*args): Allows you to pass a variable number of


positional arguments.

• Arbitrary Keyword Arguments (**kwargs): Allows for a variable number of keyword


arguments.

Example of using various types of arguments:

def func_example(a, b=2, *args, **kwargs):


print(a, b)
print(args)
print(kwargs)

func_example(1, 3, 'extra', another=4)


This example highlights how Python accommodates flexibility in function arguments, making it a
robust and versatile language for many programming paradigms.

How to get list of parameters name from a function in Python?

In this article, we are going to discuss how to get list parameters from a function in Python.
The inspect module helps in checking the objects present in the code that we have written. We are
going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the
list of parameters name of function or method passed as an argument in one of the methods.

Using inspect.signature() method

Below are some programs which depict how to use the signature() method of the inspect module to
get the list of parameters name:

Example 1: Getting the parameter list of a method.

# import required modules

import inspect

import collections

# use signature()

print(inspect.signature(collections.Counter))

Output:

(*args, **kwds)

Example 2: Getting the parameter list of an explicit function.

# explicit function

def fun(a, b):

return a**b

# import required modules

import inspect

# use signature()

print(inspect.signature(fun))

Output:

(a, b)

Example 3: Getting the parameter list of an in-built function.

# import required modules


import inspect

# use signature()

print(inspect.signature(len))

Output:

(obj, /)

Using inspect.getargspec() method

Below are some programs which depict how to use the getargspec() method of the inspect module to
get the list of parameters name:

Example 1: Getting the parameter list of a method.

# import required modules

import inspect

import collections

# use getargspec()

print(inspect.getargspec(collections.Counter))

Output:

ArgSpec(args=[], varargs=’args’, keywords=’kwds’, defaults=None)

Example 2: Getting the parameter list of an explicit function.

# explicit function

def fun(a, b):

return a**b

# import required modules

import inspect

# use getargspec()

print(inspect.getargspec(fun))

Output:

ArgSpec(args=[‘a’, ‘b’], varargs=None, keywords=None, defaults=None)

Example 3: Getting the parameter list of an in-built function.


# import required modules

import inspect

# use getargspec()

print(inspect.getargspec(len))

Output:

ArgSpec(args=[‘obj’], varargs=None, keywords=None, defaults=None)

How to get list of parameters name from a function in Python? – FAQs

What is the parameter list of a function?

The parameter list of a function consists of the variables that the function takes as inputs when it is
called. These parameters can be defined in the function’s definition and can include positional
parameters, default parameters, variable-length parameters (using *args and **kwargs), and
keyword-only parameters.

For example:

def example_function(param1, param2, *args, **kwargs):


pass

How to return a list from a function in Python?

To return a list from a function in Python, simply create the list and use the return statement to return
it.

For example:

def create_list():
my_list = [1, 2, 3, 4, 5]
return my_list

result = create_list()
print(result)

How to get the function name in Python?

To get the name of a function, you can use the __name__ attribute of the function object.

For example:

def my_function():
pass

print(my_function.__name__)

How to access variable names?

To access variable names in the current scope, you can use the locals() or globals() functions, which
return dictionaries containing the current local and global variables, respectively.
Example 2:

def no_of_argu(*args):

# using len() method in args to count

return(len(args))

print(no_of_argu(2, 5, 4))

print(no_of_argu(4, 5, 6, 5, 4, 4))

print(no_of_argu(3, 2, 32, 4, 4, 52, 1))

print(no_of_argu(1))

Output :

3
6
7
1

Returning Multiple Values in Python

Last Updated : 02 May, 2023

In Python, we can return multiple values from a function. Following are different ways 1) Using
Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values
and return an object of the class.

• Python

# A Python program to return multiple

# values from a method using class

class Test:

def __init__(self):

self.str = "geeksforgeeks"

self.x = 20
# This function returns an object of Test

def fun():

return Test()

# Driver code to test above method

t = fun()

print(t.str)

print(t.x)

Output

geeksforgeeks

20

Below are interesting methods for somebody shifting C++/Java world.

2) Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without ().
Tuples are immutable. See this for details of tuple and list.

• Python

def fun():

str = "geeksforgeeks"

x = 20

return str, x # Return tuple, we could also

str, x = fun() # Assign returned tuple

print(str)

print(x)

print(fun())

Output

geeksforgeeks

20

3) Using a list: A list is like an array of items created using square brackets. They are different from
arrays as they can contain items of different types. Lists are different from tuples as they are mutable.

def fun():

str = "geeksforgeeks"
x = 20

return [str, x]

print(fun())

Output

['geeksforgeeks', 20]

4) Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details
of dictionary.

• Python

# A Python program to return multiple

# values from a method using dictionary

# This function returns a dictionary

def fun():

d = dict();

d['str'] = "GeeksforGeeks"

d['x'] = 20

return d

# Driver code to test above method

d = fun()

print(d)

Output

{'x': 20, 'str': 'GeeksforGeeks'}

Python None Keyword

Last Updated : 26 Apr, 2023

None is used to define a null value or Null object in Python. It is not the same as an empty string, a
False, or a zero. It is a data type of the class NoneType object.

None in Python
Python None is the function returns when there are no return statements.

Python3

def check_return():

pass

print(check_return())

Output:

None

Null Vs None in Python

None – None is an instance of the NoneType object type. And it is a particular variable that has no
objective value. While new NoneType objects cannot be generated, None can be assigned to any
variable.

Null – There is no null in Python, we can use None instead of using null values.

Note: Python null is refer to None which is instance of the NoneType object type

Example:

Here we will both Null and None and we get the related output for these two statements. Where one of
the outputs is Null is not defined.

Python3

print(type(None))

print(type(Null))

Output:

<class 'NoneType'>

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

Input In [9], in <cell line: 2>()

1 print(type(None))

----> 2 print(type(Null))

NameError: name 'Null' is not defined

Referring to the null object in Python

Assigning a value of None to a variable is one way to reset it to its original, empty state.

Example 1:
We will check the type of None

Python3

print(type(None))

Output:

<class 'NoneType'>

Example 2:

Declaring a variable as None.

Python3

var = None

# checking it's value

if var is None:

print("var has a value of None")

else:

print("var has a value")

Output:

var has a value of None

Note: If a function does not return anything, it returns None in Python.

Returning a function from a function – Python

Functions in Python are first-class objects. First-class objects in a language are handled uniformly
throughout. They may be stored in data structures, passed as arguments, or used in control structures.

Properties of first-class functions:

• A function is an instance of the Object type.

• You can store the function in a variable.

• You can pass the function as a parameter to another function.

• You can return the function from a function.

• You can store them in data structures such as hash tables, lists, …

Example 1: Functions without arguments


In this example, the first method is A() and the second method is B(). A() method returns the B()
method that is kept as an object with name returned_function and will be used for calling the second
method.

# define two methods

# second method that will be returned

# by first method

def B():

print("Inside the method B.")

# first method that return second method

def A():

print("Inside the method A.")

# return second method

return B

# form a object of first method

# i.e; second method

returned_function = A()

# call second method by first method

returned_function()

Output :

Inside the method A.


Inside the method B.

Example 2: Functions with arguments

In this example, the first method is A() and the second method is B(). Here A() method is called which
returns the B() method i.e; executes both the functions.

# define two methods

# second method that will be returned


# by first method

def B(st2):

print("Good " + st2 + ".")

# first method that return second method

def A(st1, st2):

print(st1 + " and ", end = "")

# return second method

return B(st2)

# call first method that do two work:

# 1. execute the body of first method, and

# 2. execute the body of second method as

# first method return the second method

A("Hello", "Morning")

Output :

Hello and Good Morning.

Example 3: Functions with lambda

In this example, the first method is A() and the second method is unnamed i.e; with lambda. A()
method returns the lambda statement method that is kept as an object with the name returned_function
and will be used for calling the second method.

# first method that return second method

def A(u, v):

w=u+v

z=u-v

# return second method without name

return lambda: print(w * z)

# form a object of first method


# i.e; second method

returned_function = A(5, 2)

# check object

print(returned_function)

# call second method by first method

returned_function()

Output :

<function A.<locals>.<lambda> at 0x7f65d8e17158>


21

Python – Get Function Signature

Let’s consider a scenario where you have written a very lengthy code and want to know the function
call details. So what you can do is scroll through your code each and every time for different functions
to know their details or you can work smartly. You can create a code where you can get the function
details without scrolling through the code. This can be achieved in two ways –

• Using signature() function

Using signature() function

We can get function Signature with the help of signature() Function. It takes callable as a parameter
and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object
is given then it throws a Type Error.

Syntax:

inspect.signature(callable, *, follow_wrapped=True)

Example 1:

from inspect import signature

# declare a function gfg with some

# parameter

def gfg(x:str, y:int):


pass

# with the help of signature function

# store signature of the function in

# variable t

t = signature(gfg)

# print the signature of the function

print(t)

# print the annonation of the parameter

# of the function

print(t.parameters['x'])

# print the annonation of the parameter

# of the function

print(t.parameters['y'].annotation)

Output

(x:str, y:int)

x:str

<class 'int'>

Help function in Python

In Python, the help() function is a built-in function that provides information about modules, classes,
functions, and modules. In this article, we will learn about help function in Python.

help() function in Python Syntax

Syntax: help([object])

Parameters (Optional) : Any object for which we want some help or the information.

If the help function is passed without an argument, then the interactive help utility starts up on the
console.

What is Help function in Python?


The Python help function is used to display the documentation of modules, functions, classes,
keywords, etc. It provides information about modules, classes, functions, and methods. It is a useful
tool for getting documentation and assistance on various aspects of Python.

Python help() function Examples

Simple help() Program

In this example, we are using help() without any object to access documentation in Python.

help()

Output

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out

the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name ...

Help with Print Function in Python

Let us check the documentation of the print function in the Python console.

help(print)

Output

Help on built-in function print in module builtins:


print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

If a string is given as an argument

In this example, we are passing a string inside the help function to access documentation in Python.

help('gfg')

Output
No Python documentation found for 'gfg'.

Use help() to get the interactive help utility.

Use help(str) for help on the str class.

Python help() function docstring

The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the
class, method or function declaration. All functions should have a docstring.

Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or
using the help function.

def my_function():

'''Demonstrates triple double quotes

docstrings and does nothing really.'''

return None

print("Using __doc__:")

print(my_function.__doc__)

print("Using help:")

help(my_function)

Output

Using __doc__:

Demonstrates triple double quotes

docstrings and does nothing really.

Using help:

Help on function my_function in module __main__:

my_function()

Demonstrates triple double quot...


Python | yield Keyword

Syntax of the Yield Keyword in Python

def gen_func(x):

for i in range(x):

yield i

What does the Yield Keyword do?

yield keyword is used to create a generator function. A type of function that is memory efficient and
can be used like an iterator object.

In layman terms, the yield keyword will turn any expression that is given with it into a generator
object and return it to the caller. Therefore, you must iterate over the generator object if you wish to
obtain the values stored there. we will see the yield python example.

Difference between return and yield Python

The yield keyword in Python is similar to a return statement used for returning values in Python
which returns a generator object to the one who calls the function which contains yield, instead of
simply returning a value. The main difference between them is, the return statement terminates the
execution of the function. Whereas, the yield statement only pauses the execution of the function.
Another difference is return statements are never executed. whereas, yield statements are executed
when the function resumes its execution.

Advantages of yield:

• Using yield keyword is highly memory efficient, since the execution happens only when the
caller iterates over the object.

• As the variables states are saved, we can pause and resume from the same point, thus saving
time.

Disadvantages of yield:

• Sometimes it becomes hard to understand the flow of code due to multiple times of value
return from the function generator.

• Calling of generator functions must be handled properly, else might cause errors in program.

Example 1: Generator functions and yield Keyword in Python

Generator functions behave and look just like normal functions, but with one defining characteristic.
Instead of returning data, Python generator functions use the yield keyword. Generators’ main benefit
is that they automatically create the functions __iter__() and next (). Generators offer a very tidy
technique to produce data that is enormous or limitless.

def fun_generator():

yield "Hello world!!"

yield "Geeksforgeeks"
obj = fun_generator()

print(type(obj))

print(next(obj))

print(next(obj))

Output:

<class 'generator'>

Hello world!!

Geeksforgeeks

Example 2: Generating an Infinite Sequence

Here, we are generating an infinite sequence of numbers with yield, yield returns the number and
increments the num by + 1.

Note: Here we can observe that num+=1 is executed after yield but in the case of a return, no
execution takes place after the return keyword.

def inf_sequence():

num = 0

while True:

yield num

num += 1

for i in inf_sequence():

print(i, end=" ")

Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96.......

Example 3: Demonstrating yield working with a list.

Here, we are extracting the even number from the list.


# generator to print even numbers

def print_even(test_list):

for i in test_list:

if i % 2 == 0:

yield i

# initializing list

test_list = [1, 4, 5, 6, 7]

# printing initial list

print("The original list is : " + str(test_list))

# printing even numbers

print("The even numbers in list are : ", end=" ")

for j in print_even(test_list):

print(j, end=" ")

Output:

The original list is : [1, 4, 5, 6, 7]

The even numbers in list are : 4 6

Example 4: Use of yield Keyword as Boolean

The possible practical application is that when handling the last amount of data and searching
particulars from it, yield can be used as we don’t need to look up again from start and hence would
save time. There can possibly be many applications of yield depending upon the use cases.

# func to count number of given word

def print_even(test_string):

for i in test_string:

if i == "geeks":

yield i

# initializing string
test_string = " There are many geeks around you, \

geeks are known for teaching other geeks"

# count numbers of geeks used in string

count = 0

print("The number of geeks in string is : ", end="")

test_string = test_string.split()

for j in print_even(test_string):

count = count + 1

print(count)

Output

The number of geeks in string is: 3

You might also like