Python - Functions
Python - Functions
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())
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))
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:-
AboutMe("John", 20)
30
Ex 2
def sum(a, b):
return a + b
total=sum(5,sum(10,20))
print(total)
35