User-Defined Function
Calling a Function
Variable-Length Arguments
(i) args
(ii)kwargs
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)
def square( item_list ):
squares = [ ]
for l in item_list:
squares.append( l**2 )
def function( n1, n2 ):
function( 50, 30)
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
lambda_ = lambda argument1, argument2: argument1 + argument2;
print( "Value of the function is : ", lambda_( 20, 30 ) )
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_ )
Output:
The square of the number is: 81
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" ) )
Output:
Length of the string Functions is: 9
Length of the string Python is: 6
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.
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)
Output:
['PYTHON', 'FUNCTIONS', 'TUTORIAL']
[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]
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 ) )
Output:
With return statement
1521
Without return statement
None
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)
Output:
slice(None, 5, None)
slice(0, 5, 3)
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)
Output:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
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))
Output:
16
16
0.0625
0.0625
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))
Output:
10
11
7
Top comments (0)