Python Functions

FUNCTIONS

If a group of statements is repeatedly required then it is not recommended to write these statements every timeseparately.We have to define these statements as a single unit and we can call that unit any number of times based on our requirement without rewriting. This unit is nothing but function.

The main advantage of functions is code Reusability.

Note:
In other languages functions are known as methods, procedures, subroutines etc.

Python supports 2 types of functions

  1. Built in Functions
  2. User Defined Functions

Built in Functions:
The functions which are coming along with Python software automatically, are called built in functions or pre-defined functions

Ex:
id()
type()
input()
eval()
etc..

User Defined Functions:
The functions which are developed by programmer explicitly according to business requirements ,are called user defined functions.

Syntax to create user defined functions:
def function_name(parameters) :
       doc string"""
---------
---------
return value

Note:
While creating functions we can use 2 keywords

  • def (mandatory)
  • return (optional)
Ex 1: Write a function to print Hello
test.py

def wish():
    print("Hello Good Morning")
wish()
wish()
wish()

Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time of calling,compulsory we should provide values otherwise,otherwise we will get error.

Ex: Write a function to take name of the student as input and print wish message by name.

def wish(name):
    print("Hello",name," Good Morning")
wish("SEED")
wish("DHARSHI")

D:\Python_classes>py test.py
Hello SEED Good Morning
Hello DHARSHI Good Morning

Return Statement:
Function can take input values as parameters and executes business logic, and returns output to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum.

def add(x,y):
    return x+y
result=add(10,20)
print("The sum is",result)
print("The sum is",add(100,200))

D:\Python_classes>py test.py
The sum is 30
The sum is 300

If we are not writing return statement then default return value is None

Ex:
def f1():
print(“Hello”)
f1()
print(f1())

Output
Hello
Hello
None

Returning multiple values from a function:

In other languages like C,C++ and Java, function can return atmost one value. But in Python, a function can return any number of values.

Ex 1:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub
x,y=sum_sub(100,50)
print(“The Sum is :”,x)
print(“The Subtraction is :”,y)

Output
The Sum is : 150
The Subtraction is : 50

Types of arguments

def f1(a,b):
---------
---------
f1(10,20)

a,b are formal arguments where as 10,20 are actual arguments

There are 4 types are actual arguments are allowed in Python.

  • positional arguments
  • keyword arguments
  • default arguments
  • Variable length arguments

These are the arguments passed to function in correct positional order.

def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)

The number of arguments and position of arguments must be matched. If we change the order then result may be changed.

If we change the number of arguments then we will get error.

keyword arguments:
We can pass argument values by keyword i.e by parameter name.

Ex:
def wish(name,msg):
print(“Hello”,name,msg)
wish(name=”SEED”,msg=”Good Morning”)
wish(msg=”Good Morning”,name=”SEED”)

Output
Hello SEED Good Morning
Hello SEED Good Morning

Here the order of arguments is not important but number of arguments must be matched.

Note:
We can use both positional and keyword arguments simultaneously. But first we have to take positional arguments and then keyword arguments, otherwise we will get syntaxerror.

def wish(name,msg):
print(“Hello”,name,msg)
wish(“SEED”,”GoodMorning”) ==>valid

wish(“SEED”,msg=”GoodMorning”) ==>valid wish(name=”SEED”,”GoodMorning”) ==>invalid

SyntaxError: positional argument follows keyword argument

Default Arguments:
Sometimes we can provide default values for our positional arguments.

Ex:
def wish(name=”Guest”):
print(“Hello”,name,”Good Morning”)
wish(“SEED”)
wish()

Output
Hello SEED Good Morning
Hello Guest Good Morning

If we are not passing any name then only default value will be considered.

Note:
After default arguments we should not take non default arguments

def wish(name=”Guest”,msg=”Good Morning”): ===>Valid
def wish(name,msg=”Good Morning”): ===>Valid
def wish(name=”Guest”,msg): ==>Invalid

SyntaxError: non-default argument follows default argument

Variable length arguments:
Sometimes we can pass variable number of arguments to our function,such type of arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def f1(*n):

We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

Ex:
def sum(*n):
total=0
for n1 in n:
total=total+n1
print(“The Sum=”,total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)

Output
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100

Note:
We can mix variable length arguments with positional arguments.

Ex:
def f1(n1,*s):
print(n1)
for s1 in s:
print(s1)
f1(10)
f1(10,20,30,40)
f1(10,”A”,30,”B”)

Output
10
10
20
30
40
10
A
30
B

Note: After variable length argument, if we are taking any other arguments then we should provide values as keyword arguments.

Ex:
def f1(*s,n1):
for s1 in s:
print(s1)
print(n1)
f1(“A”,”B”,n1=10)

Output
A
B
10

f1(“A”,”B”,10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: ‘n1’

Types of Variables

Python supports 2 types of variables.

  1. Global Variables
  2. Local Variables

Global Variables

  • The variables which are declared outside of function are called global variables.
  • These variables can be accessed in all functions of that module.

Ex:
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1()
f2()

Output
10
10

Local Variables:

  • The variables which are declared inside a function are called local variables.
  • Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access.

Ex:
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()

NameError: name ‘a’ is not defined

global keyword:

We can use global keyword for the following 2 purposes:

  • To declare global variable inside function
  • To make global variable available to the function so that we can perform required modifications

Ex 1:
a=10
def f1():
a=777
print(a)
def f2():
print(a)
f1()
f2()

Output
777
10

Follow Us On