Functions
Functions are a convenient way to divide your code into useful blocks,
allowing us to order our code, make it more readable, reuse it and save some
time.
Python gives you many built-in functions like print(), input() etc. but you can
also create your own functions. These functions are called user-defined
functions (UDF).
Syntax : -
def functionname( parameters ):
function body
return [expression]
Example :
def printme():
print(“I am inside a function now." )
Calling a Function –
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt.
def printme():
print(“I am inside a function now." )
# Now you can call printme function
printme()
Arguments in function
The arguments are types of information which can be passed into the function.
The arguments are specified in the parentheses. We can pass any number of
arguments,
but they must be separate them with a comma.
Consider the following example, which contains a function that accepts a string as
the argument.
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func("Devansh")
Arguments in function
#Python function to calculate the sum of two variables –
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
S= sum(a,b)
print("Sum = ",s)
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value
of any of the arguments is not provided at the time of function call, then that
argument can be initialized with the value given in the definition even if the
argument is not specified at the function call.
Eg 1-
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
Eg 2 -
def printme(name,age=22):
print("My name is",name,"and age is",age)
#the variable age is not passed into the function
printme(name = "john")
#the value of age is overwritten here, 10 will be printed as age
printme(age = 10,name="David")
return Statement
Many times a programmer need to know the result of the operations performed in
a function. A return statement in a Python function serves this purpose.
When used -
1. It immediately terminates the function and passes execution control back to
the caller.
2. It provides a mechanism by which the function can pass data back to the caller.
Consider example where you need to calculate simple interest based on values
provided. The function will be –
def si (p,r, t):
int = (p* r* t )/100
return int
intEarned = si (10000, 4.5, 3)
#use interest for further calculations