Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

Python Functions

User-Defined Function
Calling a Function
Variable-Length Arguments
(i) args
(ii)kwargs
Types of function

Example of a User-Defined Function
sum = calculate_sum(5, 10)
factorial(num):
getattr()
pow()
callable()
abs()
eval()
sum()
any()
format()

def square( num ):  
 return num**2     
object_ = square(6)
Enter fullscreen mode Exit fullscreen mode
def square( item_list ):  
squares = [ ]    
for l in item_list:    
 squares.append( l**2 ) 
Enter fullscreen mode Exit fullscreen mode
def function( n1, n2 ):  
function( 50, 30)
Enter fullscreen mode Exit fullscreen mode
def function( *args_list ):    
    ans = []    
    for l in args_list:    
        ans.append( l.upper() ) 
Enter fullscreen mode Exit fullscreen mode
def function( **kargs_list ):    
    ans = []    
    for key, value in kargs_list.items():    
        ans.append([key, value])  
Enter fullscreen mode Exit fullscreen mode
lambda_ = lambda argument1, argument2: argument1 + argument2;    
print( "Value of the function is : ", lambda_( 20, 30 ) ) 
Enter fullscreen mode Exit fullscreen mode

python-tutorials-list-of-functions-of-list-datatypes
What are Python Functions?
A function is a collection of related assertions that performs a mathematical, analytical, or evaluative operation. Python functions are simple to define and essential to intermediate-level programming. The exact criteria hold to function names as they do to variable names. The goal is to group up certain often performed actions and define a function. Rather than rewriting the same code block over and over for varied input variables, we may call the function and repurpose the code included within it with different variables.

The functions are broad of two types, user-defined and built-in functions. It aids in keeping the software succinct, non-repetitive, and well-organized.

Advantages of Functions in Python
Python functions have the following benefits.

By including functions, we can prevent repeating the same code block repeatedly in a program.
Python functions, once defined, can be called many times and from anywhere in a program.
If our Python program is large, it can be separated into numerous functions which is simple to track.
The key accomplishment of Python functions is we can return as many outputs as we want with different arguments.

Example of a User-Defined Function
We will define a function that when called will return the square of the number passed to it as an argument.

Code

def square( num ):  
    """ 
    This function computes the square of the number. 
    """  
    return num**2   
object_ = square(9)  
print( "The square of the number is: ", object_ ) 
Enter fullscreen mode Exit fullscreen mode

Output:

The square of the number is:  81
Enter fullscreen mode Exit fullscreen mode

Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must be passed to the function, and structuring the code block.

After a function's fundamental framework is complete, we can call it from anywhere in the program. The following is an example of how to use the a_function function.

Code

# Defining a function  
def a_function( string ):  
    "This prints the value of length of string"  
    return len(string)  

# Calling the function we defined  
print( "Length of the string Functions is: ", a_function( "Functions" ) )  
print( "Length of the string Python is: ", a_function( "Python" ) )  
Enter fullscreen mode Exit fullscreen mode

Output:

Length of the string Functions is:  9
Length of the string Python is:  6
Enter fullscreen mode Exit fullscreen mode

Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a function. There are two types of characters that we can use for this purpose:

*args -These are Non-Keyword Arguments
**kwargs - These are Keyword Arguments.
Enter fullscreen mode Exit fullscreen mode

Here is an example to clarify Variable length arguments

Code

# Python code to demonstrate the use of variable-length arguments  

# Defining a function  
def function( *args_list ):  
    ans = []  
    for l in args_list:  
        ans.append( l.upper() )  
    return ans  
# Passing args arguments  
object = function('Python', 'Functions', 'tutorial')  
print( object )  

# defining a function  
def function( **kargs_list ):  
    ans = []  
    for key, value in kargs_list.items():  
        ans.append([key, value])  
    return ans  
# Paasing kwargs arguments  
object = function(First = "Python", Second = "Functions", Third = "Tutorial")  
print(object)  
Enter fullscreen mode Exit fullscreen mode

Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
Enter fullscreen mode Exit fullscreen mode

return Statement
We write a return statement in a function to leave a function and give the calculated value when a defined function is called.

Syntax:

return < expression to be returned as output >

An argument, a statement, or a value can be used in the return statement, which is given as output when a specific task or function is completed. If we do not write a return statement, then None object is returned by a defined function.

Here is an example of a return statement in Python functions.

Code

# Python code to demonstrate the use of return statements  

# Defining a function with return statement  
def square( num ):  
    return num**2  

# Calling function and passing arguments.  
print( "With return statement" )  
print( square( 39 ) )  

# Defining a function without return statement   
def square( num ):  
     num**2   

# Calling function and passing arguments.  
print( "Without return statement" )  
print( square( 39 ) )  
Enter fullscreen mode Exit fullscreen mode

Output:

With return statement
1521
Without return statement
None
Enter fullscreen mode Exit fullscreen mode

Some Important Function

Python bin() Function
The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.

Python bin() Function Example

x = 10

y = bin(x)

print (y)

Output:

0b1010

Python float()
The python float() function returns a floating-point number from a number or string.

Python float() Example

for integers

print(float(9))

for floats

print(float(8.19))

for string floats

print(float("-24.27"))

for string floats with whitespaces

print(float(" -17.19\n"))

string float error

print(float("xyz"))

Output:

9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'

Python len() Function
The python len() function is used to return the length (the number of items) of an object.

Python len() Function Example

strA = 'Python'

print(len(strA))

Output:

6

Python min() Function
Python min() function is used to get the smallest element from the collection. This function takes two arguments, first is a collection of elements and second is key, and returns the smallest element from the collection.

Python min() Function Example

Calling function

small = min(2225,325,2025) # returns smallest element

small2 = min(1000.25,2025.35,5625.36,10052.50)

Displaying result

print(small)

print(small2)

Output:

325
1000.25
Python set() Function
In python, a set is a built-in class, and this function is a constructor of this class. It is used to create a new set using elements passed during the call. It takes an iterable object as an argument and returns a new set object.

Python set() Function Example

Calling function

result = set() # empty set

result2 = set('12')

result3 = set('javatpoint')

Displaying result

print(result)

print(result2)

print(result3)

Output:

set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python slice() Function
Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection.

Python slice() Function Example

# Calling function  
result = slice(5) # returns slice object  
result2 = slice(0,5,3) # returns slice object  
# Displaying result  
print(result)  
print(result2)  
Enter fullscreen mode Exit fullscreen mode

Output:

slice(None, 5, None)
slice(0, 5, 3)
Enter fullscreen mode Exit fullscreen mode

Python sorted() Function
Python sorted() function is used to sort elements. By default, it sorts elements in an ascending order but can be sorted in descending also. It takes four arguments and returns a collection in sorted order. In the case of a dictionary, it sorts only keys, not values.

Python sorted() Function Example

str = "javatpoint" # declaring string  
# Calling function  
sorted1 = sorted(str) # sorting string  
# Displaying result  
print(sorted1) 
Enter fullscreen mode Exit fullscreen mode

Output:

['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Enter fullscreen mode Exit fullscreen mode

Python pow() Function
The python pow() function is used to compute the power of a number. It returns x to the power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e. (x, y) % z.

Python pow() function Example

# positive x, positive y (x**y)  
print(pow(4, 2))  

# negative x, positive y  
print(pow(-4, 2))  

# positive x, negative y (x**-y)  
print(pow(4, -2))  

# negative x, negative y  
print(pow(-4, -2)) 
Enter fullscreen mode Exit fullscreen mode

Output:

16
16
0.0625
0.0625
Enter fullscreen mode Exit fullscreen mode

Python round() Function
The python round() function rounds off the digits of a number and returns the floating point number.

Python round() Function Example

#  for integers  
print(round(10))  

#  for floating point  
print(round(10.8))  

#  even choice  
print(round(6.6))  
Enter fullscreen mode Exit fullscreen mode

Output:

10
11
7
Enter fullscreen mode Exit fullscreen mode

Types of function

Anonymous Functions (Lambda Functions):

Definition: Functions that are defined without a name using the lambda keyword.

Syntax:

lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode

Example:

add = lambda x, y: x + y
print(add(2, 3))  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Quick one-liner functions.

Functions used as arguments to higher-order functions like map(), filter(), and sorted().

  1. Regular Functions (Def Functions):

Definition: Functions that are defined using the def keyword with a name.

Syntax:

def function_name(parameters):
    # function body
    return value
Enter fullscreen mode Exit fullscreen mode

Example:

def add(x, y):
    return x + y
print(add(2, 3))  # Output: 5
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used for defining reusable blocks of code.

Functions with complex logic or multiple statements.

  1. Recursive Functions:

Definition: Functions that call themselves.

Syntax:

def recursive_function():
    if condition:
        return base_case
    else:
        return recursive_function()
Enter fullscreen mode Exit fullscreen mode

Example (Factorial):

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
print(factorial(5))  # Output: 120
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used in problems that can be broken into smaller subproblems (like tree traversal, divide and conquer algorithms).

Higher-order Functions:

Definition: Functions that take other functions as arguments or return them as results.

Example:

def apply_function(f, x):
    return f(x)

def square(x):
    return x * x

print(apply_function(square, 3))  # Output: 9
Enter fullscreen mode Exit fullscreen mode

Use Cases:

When you need to pass functions as parameters or return functions from other functions.

Functional programming style.

Generator Functions:

Definition: Functions that use the yield keyword to return an iterable generator object.

Syntax:

def generator_function():
    yield value
Enter fullscreen mode Exit fullscreen mode

Example:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for number in countdown(5):
    print(number)
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used when dealing with large datasets or streams of data where you don’t want to store all the values in memory.

Lambda Functions with Multiple Expressions:

Definition: A variation of lambda functions where you use logical expressions within them (only one expression is allowed).

Example:

max_value = lambda x, y: x if x > y else y
print(max_value(5, 10))  # Output: 10
Enter fullscreen mode Exit fullscreen mode

Closure Functions:

Definition: Functions that are defined within another function and remember the values from the enclosing function's scope.

Syntax:

def outer_function(outer_variable):
    def inner_function(inner_variable):
        return outer_variable + inner_variable
    return inner_function
Enter fullscreen mode Exit fullscreen mode

Example:

def multiply_by(n):
    def multiplier(x):
        return x * n
    return multiplier

multiply_by_5 = multiply_by(5)
print(multiply_by_5(10))  # Output: 50
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Useful for creating function factories and handling data encapsulation.

Built-in Functions:

Definition: Python provides several built-in functions that can be used without needing to define them.

Example:

print()

len()

sum()

sorted()
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Everyday operations like printing, sorting, or finding lengths of data structures.

Partial Functions:

Definition: Functions created using the functools.partial() function to fix a certain number of arguments of a function and generate a new function.

Syntax:

from functools import partial

Example:

def power(base, exponent):
    return base ** exponent

cube = partial(power, exponent=3)
print(cube(2))  # Output: 8
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Used for creating a function with some arguments preset.

Function with Variable Number of Arguments:

Definition: Functions that can accept any number of arguments using *args for positional arguments and **kwargs for keyword arguments.

Syntax:

def func(*args, **kwargs):
    # handle arguments
Enter fullscreen mode Exit fullscreen mode

Example:

def add(*args):
    return sum(args)

print(add(1, 2, 3))  # Output: 6
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Functions that need to handle a dynamic number of arguments, like when working with a variable-length list of items.

Static Methods:

Definition: Methods that do not require an instance to be called. They can be called on the class itself.

Syntax:

class MyClass:
    @staticmethod
    def my_static_method():
        pass
Enter fullscreen mode Exit fullscreen mode

Example:

class MyClass:
    @staticmethod
    def greet(name):
        return f"Hello, {name}!"

print(MyClass.greet("Alice"))  # Output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

Use Cases:

When the method doesn't rely on instance attributes and doesn't modify the state of the object.

Top comments (0)