Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Variables, Expression and...
  5. Function
  6. User Defined function

User Defined function

User defined functions are the functions that programmers create for their requirement and use. These functions can then be combined to form module which can be used in other programs by importing them

Advantages

  • Helps to divide a program into modules. This makes the code easier to manage, debug and scale
  • It implements code reusability
  • Allows to change functionality easily and different programmers can work  on different functions

Function Definition (Creating a function )

Syntax

  • A function is defined using def keyword
def function_name( parameter 1, parameter 2,…, parameter n)
	Statement 1
	Statement 2
 	Statement n
	return [expression]
  • def keyword is used to define a function
  • Function name is followed after the def keyword followed by parenthesis in which arguments are given
  • End with colon ( : )
  • Inside the function add the program statements to be executed
  • End with or without return statement

Function Calling (Calling a function)

  • Once the function is defined, one can call it from another function, program or even from python prompt
  • To call a function, type the function name with appropriate arguments

Syntax

function_name( argument 1, argument 2,…, argument n)

docstring

  • Docstring is short for documentation string
  • It is a string that occurs as the first statement in a module, function, class or method definition
  • It is must to write what a function / class does in the docstring
  • Triple quotes are used while writing docstrings

Syntax

functionname.__doc__

Example

def cube(num):
    """ Function to find cube of a number"""
    return num*num*num
print(cube(5))
print(cube.__doc__)

Output

125
 Function to find cube of a number

return Expression

A function returns a value, using the return statement

return expression

Flow of Execution

  • The order in which statements are executed is called flow of execution
  • Execution always begins at the first statement of the program
  • Statements are run one at a time from top to bottom
  • Function definition do not alter the flow of execution of the program but the statements inside the function will run only when the function is called
  • When the function is called, the flow jumps to the body of the function and after the statements are executed the flow of execution returns to the place from where it is called

Example

def my_mul(a,b):
    c = a*b
    return c
print("Multiplying two numbers")
x = int(input("Enter a number"))
y = int(input("Enter another number"))
d=my_mul(x,y)
print("result = ",d)

Loading

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments