Functions in Python

03 Nov Functions in Python


Introduction

function is a group of related statements that perform a specific task.
It provides better modularity and code reusability.
Functions are divided into 2 categories:
built-in-function
user defined function
built-in-functions are language’s own functions or pre-defined functions. In this case these are python interpreter’s function that are always available for use

User defined function are those functions which are defined by the user at the time of writing program.
Syntax for defining a function

def function_name(): 	# Function Header
	statement	# Function block
	statement


1. Keyword def marks the start of function header.
2. Function_name should be a unique and meaningfull identifier that shows the purpose of function. Name should follow the rules of writing identifiers.
3. A colon (:) to mark the end of function header.
4. One or more valid python statements that make up the function body. Statements must have same indentation level.

How to define a function?

follow the syntax that we have discussed in the previous section and let’s create
a simple function to say “Hello World”.

def message():
	print('Hello World')

How to call a function?

Once we have defined a function, we need to call the function to execute it. Otherwise
function will be there in program but won’t work.Now let’s see complete program with the definition
and the calling statement of the function

def message():
	print('Hello World')
message()   # function call


Output:
Hello World


Passing Arguments to a function

An argument is any piece of data that is passed into a function when the
function is called.
A parameter is a variable that receives an argument that is passed into a function.
sometimes, while calling a function we need to pass the value of a variable that we may asked from the user or it could be the calculation of some other expression.

Function_call

Function Calling and Passing Arguments

Function Returning Values

A value-returning function has a return statement that returns a value
back to the part of the program that called it.
A value-returning function must have a return statement. Here is the example

def add(num1, num2):
    result = num1 + num2
    return result  	#return statement

a=int(input("Enter first Number"))
b=int(input("Enter second Number"))
sum=add(a,b) #Function call
print("addition is", sum)


Enter first Number 4

Enter second Number 5
addition is 9


The return statement can return the value of an expression, you can eliminate the result variable and rewrite the function as:

def sum(num1, num2):
return num 1 + num 2

No Comments

Post A Comment

Powered by themekiller.com anime4online.com animextoon.com apk4phone.com tengag.com moviekillers.com