Functons in Python
Functons in Python
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 : -
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." )
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.
a = int(input("Enter a: "))
b = int(input("Enter 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)
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 –