ü Python
has many built-in functions like print(), input(), len(). Besides built-ins you
can also create your own functions to do more specific jobs—these are called
user-defined functions.
How We can Defining and calling
simple functions In Python
def function_name(parameters):
statement(s)
Points to remember
§ Use the def
keyword to define a function, followed by the name of the function. The name of
the function should be followed by parentheses ().
§ Function
parameters are optional. The parameter names must be with in parentheses
separated by commas.
#Here’s an example of
a simple function definition
def greet():
print('Hello Python')
#Now let’s call the defined
greet() function:
greet()
Components of a Function
Basically, there are two types of arguments:
Actual arguments
Formal arguments
Formal
arguments
§
The variables declared
within the parentheses following the function name in a function declaration or
definition are known as Formal arguments
Actual arguments
§
the values that are passed
within the parentheses of a function call are known as Actual arguments.
1. Method with out return type and without arguments.
#Here’s an example of a simple
function definition
def add():
a=10
b=20
c=a+b
print('Sum= ',c)
#Now let’s call the defined
add() function:
add()
2. Method without
return type and with arguments.
§ parameters
is an optional list of identifiers that get bound to the values supplied as
arguments when the function is called.
§ A
function may have an arbitrary number of arguments which are separated by
commas.
#Method with out
return type and with arguments.
def add(a,b):
c=a+b
print('sum=
',c)
#Now let’s call the defined
add() function:
add(10,20)
3. Method with return
type and without arguments.
§ A
function which doesn’t wants to return some result after performing the task
such type method is known as non-return type function.
§ A
function which wants to return some result after performing the task such type
method is known as return type function.
§ Python
functions can return values of any type via the return keyword.
#Method with return type and with out arguments.
def add():
a=10
b=20
c=a+b
return c
#Now let’s call the defined add() function:
res=add()
print('sum= ',res)
§ You'll
notice that unlike many other languages, you do not need to explicitly declare
a return type of the function.
§ Python
functions can return values of any type via the return keyword. One function
can return any number of different types!
#Method with return type
and without arguments.
def many_types(x):
if x
< 0:
return "Hello!"
else:
return 0
#Now let’s call the defined many_types function:
print(many_types(1))
print(many_types(-1)
# Output:
0
Hello!
4. Method with return
type and with arguments.
#Method with return type
and with arguments.
def add(a,b):
c=a+b
return c
#Now let’s call the defined add() function:
res=add(10,20)
print('sum= ',res)