November 10, 2019

Python tutorial 11 | user defined functions

Moving on with Python Tutorials for Beginners. This Python beginner tutorial explains how to write user-defined functions in Python programming with examples. Please view the Python video tutorial 11 or read on...

Functions allow us to avoid code repetition. We already know about string functions like lower, upper and capitalize and math functions like ceil, floor and trunc. We can define our own functions (called user-defined functions) in Python programming language.

A Python user defined function may have one or more parameters. The function parameters provide data to the function code. The function may produce different outputs based on the parameter values it receives in the function call. A Python user-defined functions may have documentation that explains it. The function definition syntax is:

def function_name (parameters):
    doc string
    code block
    return return_value

Note the def keyword that we use to define the function. The parameters are optional. The function body has the documentation string (the doc string), code block and the return statement. Now, let us see Python function examples.

# define function in Python
def average (x, y):
    sum = x + y
    return sum/2

# Python code example
# function call prints 3.5, which is the average of the arguments 3 and 4
print(average(3, 4))
# function call prints 150.0, which is the average of the two arguments
print(average(100, 200))

# define function in Python to convert kilograms to pounds
# Also, give the default parameter value as 0
def convert_weight(kilos=0):
    """Convert kilos weight to pounds weight""" # doc string
    pounds = 2.205 * kilos
    return pounds

# Python code example
# In the function call, the data is given via the argument(s) (called parameter(s) in the function definition)
# function call prints 2.205, which is the value given by the function return statement
print(convert_weight(1))

# more Python examples
# function call with no argument
# the default argument value is 0 (Note kilos=0 in the function definition above), function call prints 0.0
print(convert_weight())

# the user defined function can be called any number of times, even within a loop
for i in range(1, 6):
    print(i, 'kilo(s) is', convert_weight(i), 'pounds')

Want to see such Python samples working? View my Python video tutorial 11. Thank you.

2 comments:

  1. This is really a wonderful blog and I personally recommend to my friends. I’m sure they’ll be benefited from this site Keep update more excellent posts. We would like to tell you we do provide Android App Development Services , AngularJS Development Services React native Development Services, Python Development Services etc.

    ReplyDelete

Note: Only a member of this blog may post a comment.