How to Define and Use Python Functions

In this example, we will learn how to use functions in Python.

2. Definition of Functions

  • The function code block begins with the def keyword,  followed by the function identifier name and parameters.
  • Arguments need to be placed between the parentheses ().
  • Return [expression] returns a value to the caller. Return without expression is equivalent to returning None.

Syntax of the function:

def function_name( parameters ):

   return [expression]

Source Code

  • Example 1 (No parameter):
#define function
def getName():
    Str=input('please input your name:')
    print('your name is ', Str)

# invoke the function


please input your name: John
your name is John
  • Example 2 (multiple parameters):
#define function
def getSum(a, b):
    tmp = a + b;
    return tmp

x = int(input('Please input the first value: '))
y = int(input('Please input the second value: '))

# invoke this function
print('The sum of %d and %d is %d '%(x, y, getSum(x, y)))


Please input first value: 3
Please input second value: 2
The sum of 3 and 2 is 5
Notify of
Inline Feedbacks
View all comments