Functions with Parameters and use of return values

05 min read

Often certain variables/ parameters need to be passed into the function such that the function could perform the operations dependent on the parameters passed to obtain the right results. 

To understand better, let us consider the following example:

Task: Write a program to greet a person based on the user-specified language using functions in Python.

def greet(lang):                                 #a function names greet is declared and a parameter lang is passed with it.
if lang =='es':
print('Hola') # depending on the parameter lang, the conditional statements are executued.
elif lang == 'fr':
print('Bonjour') # observe the indentations to know the length of the loops.
else:
print('Hello')
print(greet('en'), 'Glen')
print(greet('fr'), 'FACE Prep') # the function is called with the parameter lang=='fr'.
Output:

Hello Glen
Bonjour FACE Prep

 

We can also use return values to directly output the results from the defined function into the user-defined variables or position of the program. For example, the same program can be written using return variables as:

def greet(lang):                                 #a function names greet is declared and a parameter lang is passed with it.
if lang =='es':
return 'Hola' # depending on the parameter lang, the conditional statements are executued and results are returned.
elif lang == 'fr':
return 'Bonjour' # observe the indentations to know the length of the loops.
else:
return 'Hello'
print(greet('en'), 'Glen')
print(greet('fr'), 'FACE Prep') # the function is called with the parameter lang=='fr'.
Output:

Hello Glen
Bonjour FACE Prep

Now consider another example where we use multiple input parameters for the functions.

 

Task: Write a simple program to add two numbers using functions in Python:

def add_two_no(a,b):             #a function is defined with 2 parameters.
added= a+b # the two parameters are added.
return added # their sum is returned back
x=add_two_no(3,5) # the returned value is stored in variable x
print(x)
Output:
8

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error