How to Define and Use Python Functions


In this example we will show 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 ):

   function_suite
   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
getName()

Output:

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)))

Output:

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