Functions_Advanced[1]
Functions_Advanced[1]
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
• Positional 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:
def myFun(*argv):
print(arg)
Output:
Hello
Welcome
to
GeeksforGeeks
Example 2:
Output
Argument *argv : to
Example:
def fun(*args):
print(arg)
fun(1, 2, 3, 4, 5)
Output
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):
print(f"{k}: {val}")
Output
name: Alice
age: 30
• Inside the function, you can iterate over the dictionary and print the key-value pairs.
Pydef myFun1(*argv):
print (arg)
def myFun2(**kwargs):
# Driver code
print("\nResult of **kwargs")
Output:
Result of *args:
Hello
Welcome
to
GeeksforGeeks
Result of **kwargs
mid == for
first == Geeks
last == Geeks
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 greet(self):
p1 = Person("Alice", 30)
p1.greet()
Output
def myFun(**kwargs):
# Driver code
Output:
first == Geeks
mid == for
last == Geeks
We can use both *args and **kwargs in the same function to accept a mix of positional and keyword
arguments.
Example:
Output
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).
The * operator allows us to pass multiple arguments to a function and pack them into a tuple.
Example Code:
def sample(*args):
Output
Code
def sample(**kwargs):
Output
Unpacking Arguments
Unpacking allows values from an iterable (list, tuple, or dictionary) to be passed as separate
arguments to a function.
Example
return a + b + c
result = addition(*num)
print("Sum:", result)
Output
Sum: 16
Example
info(**data)
Output
Example
print("Positional:", args)
Output
Positional: (1, 2, 3)
Explanation:
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__)
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
print(evenOdd.__doc__)
Output:
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.
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.
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.
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:
self.name = name
self.age = age
print(person.age) # Output: 30
In this example, __init__ initializes the name and age attributes of the Person class.
*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)
def sum_values(*args):
total = sum(args)
return total
result = sum_values(1, 2, 3, 4, 5)
print(result) # Output: 15
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.
def f1():
def f2():
print(s)
f2()
# Driver's code
f1()
Output:
I love GeeksforGeeks
• Built-in function
• User-defined function
• Recursive functions
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.
print(cube(7))
print(cube_v2(7))
Output:
343
343
s1 = 'GeeksforGeeks'
print(s2(s1))
Output
GEEKSFORGEEKS
Let’s see some of the practical uses of the Python lambda function.
Example:
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:
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.
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 list comprehension iterates through li and applies the lambda to each element.
lambda functions can incorporate conditional logic directly, allowing us to handle simple decision
making within the function.
Example:
print(check(4))
print(check(7))
Output
Even
Odd
Explanation:
• This approach is useful for labeling or categorizing values based on simple conditions.
Example:
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().
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:
n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even))
Output
[2, 4, 6]
Explanation:
def even(n):
return n % 2 == 0
a = [1, 2, 3, 4, 5, 6]
b = filter(even, a)
print(list(b))
Output
[2, 4, 6]
Explanation:
• 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.
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.
We can combine filter() with other Python functions like map() or use it in a pipeline to process data
efficiently.
a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)
c = map(lambda x: x * 2, b)
print(list(c))
Output
[4, 8, 12]
Explanation:
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.
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.
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.
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.
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
map(function, iterable)
Parameter:
Note: We can also pass multiple iterables if our function accepts multiple arguments.
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]
def double(val):
return val*2
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.
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]
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.
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]
Converting to uppercase
This example shows how we can use map() to convert a list of strings to uppercase.
print(list(res))
Output
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.
In this example, we use map() to extract the first character from each string in a list.
print(list(res))
Output
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.
res = map(str.strip, s)
print(list(res))
Output
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.
In this example, we use map() to convert a list of temperatures from Celsius to Fahrenheit.
print(list(fahrenheit))
Output
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:
a = [1, 2, 3, 4]
b = map(lambda x: x * 2, a)
print(list(b))
Output
[2, 4, 6, 8]
Explanation:
Example:
a = [1, 2, 3, 4]
b = reduce(lambda x, y: x * y, a)
print(b)
Output
24
Explanation:
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.
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.
Syntax of reduce()
• function: A function that takes two arguments and performs an operation on them.
• 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.
When paired with a lambda function, reduce() becomes a concise and powerful tool for aggregation
tasks like summing, multiplying or finding the maximum value.
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.
• 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.
import functools
import operator
# initializing list
a = [1, 3, 5, 6, 2]
print(functools.reduce(operator.add, a))
print(functools.reduce(operator.mul, a))
Output
17
180
geeksforgeeks
Explanation:
• The operation works similarly to the lambda example but the code is cleaner and more
readable.
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.
To use the reduce() function, you need to import it from the functools module.
You can import the reduce function from the functools module using the following import statement:
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.
• 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):
f = msg
print(f("Anurag"))
Output
Hello, Anurag!
Explanation:
• 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
Example:
def msg(name):
return fun2(name)
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.
A function can return another function, allowing for the creation of function factories.
Example:
def fun1(msg):
def fun2():
return fun2
print(func())
Output
Explanation:
• func stores the returned fun2, which can then be called later.
Example:
return x + y
return x - y
d={
"add": add,
"subtract": subtract
print(d["subtract"](5, 3))
Output
Explanation:
• Functions are accessed and called from the dictionary using their respective keys.
• Potential for errors: Errors in logic or implementation can lead to bugs and unexpected
behavior.
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:
• Python3
# initializing function
def GFG():
return "You just called for success !!"
# using function.__name__
Output :
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():
# using function.func_name
Output :
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
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():
frame = inspect.currentframe()
return frame.f_code.co_name
Output
This approach has a time complexity of O(1) and an auxiliary space of O(1).
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.
• Python3
print(f_func())
Output:
GEEKSFORGEEKS
• Python3
# function at run-time
f_code = compile('def gfg(a, b): return(a + b) ', "<int>", "exec")
val1 = 3999
val2 =4999
print(f_func(val1, val2))
Output:
8998
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.
# function definition
print(add(2, 3))
print(add(float(2), float(3)))
Output:
# function definition
print(concatenate(111, 100))
10
11
12
# defining the datatypes as string
13
print(concatenate(str(111), str(100)))
211
Output:
To define data types explicitly in function parameters, you use type annotations. Here’s an example of
how to annotate a function:
In this example, a and b are expected to be integers, and the function is expected to return an integer.
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:
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:
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".
Below, are the ways to access a function variable outside the function without using Global in Python.
• Using a Class
• Using a Decorator
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
result = get_variable()
print(result)
Output
42
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
original_var = 5
modified_var = modify_variable(original_var)
print(modified_var)
Output
15
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
holder = VariableHolder()
print(holder.var)
Output
42
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):
wrapper.variable = result
return result
return wrapper
@store_variable
def get_variable():
return 42
get_variable()
print(get_variable.variable)
Output
42
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.
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
Use the return statement to get a value out of a function. For example:
sum_result = add(3, 4)
print(sum_result) # Output: 7
Use the return statement to get something out of a function. For example:
def get_info():
name = "Alice"
age = 30
return name, age
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):
return(len(args))
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.
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
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
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
print(greeting)
greet(shout)
greet(whisper)
Output
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
# defining a decorator
def hello_decorator(func):
def inner1():
func()
def function_to_be_used():
function_to_be_used = hello_decorator(function_to_be_used)
function_to_be_used()
Output:
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.
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}!"
This example demonstrates how a function can be passed as an argument (callback) to another
function (process_user) and then executed within that function.
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!")
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().
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:
This function multiply takes two arguments, x and y, and returns their product.
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:
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.
Below are some programs which depict how to use the signature() method of the inspect module to
get the list of parameters name:
import inspect
import collections
# use signature()
print(inspect.signature(collections.Counter))
Output:
(*args, **kwds)
# explicit function
return a**b
import inspect
# use signature()
print(inspect.signature(fun))
Output:
(a, b)
# use signature()
print(inspect.signature(len))
Output:
(obj, /)
Below are some programs which depict how to use the getargspec() method of the inspect module to
get the list of parameters name:
import inspect
import collections
# use getargspec()
print(inspect.getargspec(collections.Counter))
Output:
# explicit function
return a**b
import inspect
# use getargspec()
print(inspect.getargspec(fun))
Output:
import inspect
# use getargspec()
print(inspect.getargspec(len))
Output:
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:
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)
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__)
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):
return(len(args))
print(no_of_argu(2, 5, 4))
print(no_of_argu(4, 5, 6, 5, 4, 4))
print(no_of_argu(1))
Output :
3
6
7
1
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
class Test:
def __init__(self):
self.str = "geeksforgeeks"
self.x = 20
# This function returns an object of Test
def fun():
return Test()
t = fun()
print(t.str)
print(t.x)
Output
geeksforgeeks
20
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
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
def fun():
d = dict();
d['str'] = "GeeksforGeeks"
d['x'] = 20
return d
d = fun()
print(d)
Output
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
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'>
---------------------------------------------------------------------------
1 print(type(None))
----> 2 print(type(Null))
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:
Python3
var = None
if var is None:
else:
Output:
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.
• You can store them in data structures such as hash tables, lists, …
# by first method
def B():
def A():
return B
returned_function = A()
returned_function()
Output :
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.
def B(st2):
return B(st2)
A("Hello", "Morning")
Output :
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.
w=u+v
z=u-v
returned_function = A(5, 2)
# check object
print(returned_function)
returned_function()
Output :
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 –
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:
# parameter
# variable t
t = signature(gfg)
print(t)
# of the function
print(t.parameters['x'])
# of the function
print(t.parameters['y'].annotation)
Output
(x:str, y:int)
x:str
<class 'int'>
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.
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.
In this example, we are using help() without any object to access documentation in Python.
help()
Output
If this is your first time using Python, you should definitely check out
Let us check the documentation of the print function in the Python console.
help(print)
Output
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'.
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():
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
Output
Using __doc__:
Using help:
my_function()
def gen_func(x):
for i in range(x):
yield i
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.
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.
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 "Geeksforgeeks"
obj = fun_generator()
print(type(obj))
print(next(obj))
print(next(obj))
Output:
<class 'generator'>
Hello world!!
Geeksforgeeks
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():
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.......
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]
for j in print_even(test_list):
Output:
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.
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, \
count = 0
test_string = test_string.split()
for j in print_even(test_string):
count = count + 1
print(count)
Output