Python -
Functions
https://www.onlinegdb.co
m/online_python_compiler
Functions
A function is a reusable block of
programming statements designed to
perform a certain task.
To define a function, Python provides
the def keyword
Syntax
def function_name(parameters):
statement1
statement2 ... ...
return [expr]
Functions that we define ourselves to do
certain specific task are referred as
user-defined functions.
Functions that readily come with Python
are called built-in functions.
Writing user-defined functions in Python
Step 1: Declare the function with the
keyword def followed by the function name.
Step 2: Write the arguments inside the
opening and closing parentheses of the
function, and end the declaration with a
colon.
Step 3: Add the program statements to be
executed.
Step 4: End the function with/without return
statement.
Creating a Function
def SayHello():
print ("Hello! Welcome to Python")
return
print(SayHello())
Hello! Welcome to Python
Function with Parameters
def SayHello(name):
print ("Hello {}!.".format(name))
return
print(SayHello('john'))
Hello john!.
Function – Add 2 numbers
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1,
num2))
('The sum is', 11)
def result(m1,m2,m3):
total=m1+m2+m3
percent=total/3
if percent>=50:
print ("Result: Pass")
else:
print ("Result: Fail")
return
p=int(input("Enter your marks in physics: "))
c=int(input("Enter your marks in chemistry: "))
m=int(input("Enter your marks in maths: "))
result(p,c,m)
Output
Enter your marks in physics: 50
Enter your marks in chemistry: 60
Enter your marks in maths: 70
Result: Pass
Enter your marks in physics: 30
Enter your marks in chemistry: 40
Enter your marks in maths: 50
Result: Fail
Parameter with Default Value
def SayHello(name='Guest'):
print ("Hello " + name)
return
print(SayHello())
Hello Guest
Parameter with given Value
def SayHello(name='Guest'):
print ("Hello " + name)
return
print(SayHello('tom'))
Hello tom
Function with Keyword Arguments
Inorder to call a function with arguments, the same
number of actual arguments must be provided.
Ex:-
def AboutMe(name, age):
print ("Hi! My name is {} and I am {}
years
old".format(name,age))
AboutMe("John", 20)
Hi! My Name is John and I am 20 years old
AboutMe(age=23, name="Mohan")
Hi! My name is Mohan and I am 23 years
old
Function with Return Value
A user-defined function can also be made
to return a value to the calling
environment by putting an expression in
front of the return statement.
In this case, the returned value has to be
assigned to some variable.
Ex:-
def sum(a, b):
return a + b
print(sum(10,20))
30
Ex 2
def sum(a, b):
return a + b
total=sum(5,sum(10,20))
print(total)
35