Functions in Python, as in any other Programming language is used to run a block of code multiple times that is defined to run. by just calling the function instead of repeating the code multiple times.

Functions help in reducing code redundancy and improves modularity. The below examples should help to get you started on defining and using functions.

Defining a function

Lets define a function that prints “hello!” whenever it is called

>>> def function_test():
...     print("hello!")
...
>>> function_test()
hello!
>>>

Defining a function to accept parameters

A function can be defined to accept parameters that can be used in it. For instance, this function will take the name and age as parameters and use it in a print statement.

>>> def function_test(name,age):
...     print "Name is %s, Age is %s" % (name, age)
...
>>> function_test('vijay', '16')
Name is vijay, Age is 16
>>> function_test('Ryan', '26')
Name is Ryan, Age is 26

Using a return statement to return a value in a function

>>> def function_test(name):
...     return name
...
>>> function_test('Vijay')
'Vijay'
>>>

Function Example : Define a function to register name and age to a Python dictionary

Putting it all together, Lets define a function that registers a “name and age” to a Dictionary.
NOTE: Python Dictionary is a datatype that functions like associative arrays that records key value pairs.

>>> registry = {'john': 45, 'Ram': 21, 'singh': 32}
>>> print(registry)
{'singh': 32, 'john': 45, 'Ram': 21}
>>> def function_register(name, age):
...     registry[name] = age
...     print "added %s %s" % (name, age)
...
>>> function_register("vinay", "36")
added vinay 36
>>> print(registry)
{'vinay': '36', 'singh': 32, 'john': 45, 'Ram': 21}
>>>
>>> function_register("victor", "29")
added victor 29
>>>
>>> print(registry)
{'vinay': '36', 'singh': 32, 'john': 45, 'Ram': 21, 'victor': '29'}
>>>

This site uses Akismet to reduce spam. Learn how your comment data is processed.