Functions
Functions
2 Types of Functions
There are mainly two types of functions in python:
• Built-in library functions: These are standard functions in python that are available to use.
• User-defined function: We can create our own functions based on our requirements.
Parameters: are the variables that are defined when the function is declared.
Arguments: are the values passed inside the parenthesis of the function when it is called.
A function can have any number of arguments separated by a comma; it can even have no
arguments. The arguments of a functions can be of many types:
1
CS 101, Fall 2024 Iteration
• Keyword/Named Arguments: The idea is to allow the caller to specify the argument name
with values so that the caller does not need to remember the order of parameters.
def student ( firstname , lastname ) :
print ( firstname , lastname )
student ( firstname = ’ Geeks ’ , lastname = ’ Practice ’)
student ( lastname = ’ Practice ’ , firstname = ’ Geeks ’)
In the above example, even though the order of arguments is different in the 2 class, the
output will be the same because the arguments are used by name.
• Positional Arguments: If you forget the order of the arguments or change the positions of
values, the output will be incorrect. To elaborate on this, an example is provided below:
def nameAge ( name , age ) :
print ( " Hi , I am " , name )
print ( " My age is " , age )
# You will get correct output because a r g u m e n t is given in order
nameAge ( " Suraj " , 27 )
# You will get i n c o r r e c t output because a r g u m e n t is not in order
nameAge ( 27 , " Suraj " ) # name and age will be swapped
Moreover, some functions are fruitful functions, which means they return some value when they
are called. In contrast, void functions perform some action but do not return any value. All the
functions provided above as examples are void functions as they do not return any value. An
example of a fruitful function is provided below:
def CalAge ( birth_year , current_year ) :
age = current_year - birth_year
return age
print ( CalAge ( 2002 , 2023 ) ) # 21 will be printed , the value r e t u r n e d can be used
d i r e c t l y to print .
Page 2 of 2