Introduction to function
What is function
-Function consists of a group of statements
-Its main function is to perform one intended job. For example creating a function to calculate area of a circle
Examples of built-in function in Python
-print() : Use to display output on screen
-input() : Taking input from user
-sqrt() : To calculate square root
Can we create user defined function
-Yes
What is user defined function
-Function which are created by programmers
Advantages of using function
-Same function can be called multiple times which causes to reduce length of a program
-Function can be easily added, deleted or modified
-Debugging becomes easy
How to define or create a function
-To create a function use keyword def followed by function name.
-After function name, write parenthesis() which may or may not contain parameters
-Include colon after parenthesis
Syntax
def function_name(parameter1, parameter2):
Example : Create a function to calculate sum of two values
def sum(a,b): result = a+b print(result)
In above lines, sum is the name of the function. a and b are parameters. Parameters receives data from outside or when the function is called
How function can be called or executed
-Use function name to call it
-In order to call sum(), use it function name such as sum()
-Passed necessary values inside parenthesis
sum(10,4)
def sum(a,b): print('Value of a parameter:',a) print('Value of b parameter:',b) result = a+b print(result)
sum(10,4) #Function is called. Passing two values to a and b parameters. Value 10 and 4 will be passed onto parameter a and b respectively.
Output
Value of a parameter: 10 Value of b parameter: 4 Sum of 10 and 4 is 14