Skip to content

Instantly share code, notes, and snippets.

@Chizaram-Igolo
Last active December 15, 2020 14:20
Show Gist options
  • Save Chizaram-Igolo/39f3c58532ee607088cda95b6c12568c to your computer and use it in GitHub Desktop.
Save Chizaram-Igolo/39f3c58532ee607088cda95b6c12568c to your computer and use it in GitHub Desktop.
# After going through this Gist file you would have learnt:
#
# 1) How to define functions and why they are important.
# 2) What Parameters and Arguments are and how to use them in functions.
# 3) Types of Functions.
# A Function is a block of statement(s) that can be used more than once.
# Functions make it easy to decouple and resuse our code.
# Rule of Thumb
# If you repeat something more than once, then you need to put it in a
# function.
# Consider the following:
# Let's get the square of the first 5 prime numbers:
num = 2
square_of_num = num * num
print(square_of_num)
num = 3
square_of_num = num * num
print(square_of_num)
num = 5
square_of_num = num * num
print(square_of_num)
num = 7
square_of_num = num * num
print(square_of_num)
num = 11
square_of_num = num * num
print(square_of_num)
# These would all work but the problem is that we've repeated the same
# arithmetic expression and print statements 5 times.
# This is bad because it is difficult to manage.
# For example, If we make a mistake somewhere, we have to correct it in
# 5 places. It also makes the code unnecessarily verbose.
# In Programming, there is a standard principle called DRY meaning:
# "Don't Repeat Yourself".
# We will keep to this principle because it saves us work and time.
#-----------Defining Functions-----------#
# We can simplify the above by putting it in a function.
# In order to have a function, we need to define it.
# We define a function using the `def` keyword, the function's name
# and a pair of parentheses with parameters (optional) and
# colon followed by an indented body. Naming rules of variables apply to
# function names.
# This function below has no parameters. To make your code easier to read,
# give 2 linespaces before and after the function.
def my_func():
print("This is my function.")
# Now we can use it by calling it. To call it, write the name of the function
# with parentheses.
# If the function has defined parameters, pass them in between the parentheses.
# This function has no arguments:
my_func()
# The good thing about this is that wheneber we want to print
# `This is my function`, we don't have to repeat the print statement,
# we can call the function as many times as we want:
my_func()
my_func()
my_func()
my_func()
my_func()
# Generally, you define and call a function this way.
# def my_func(par1, par2):
# do something
#
# Calling it:
# my_func(val1, val2)
#-----------Parameters and Arguments-----------#
# Parameters:
# These are variables defined in the parentheses of the
# function definition.
# They are local to the function, i.e. only the function can see and
# use these variables.
# Arguments:
# These are the values specified in the function call. These values are then
# assigned to the parameters in the function definintion in the order in which
# they are passed.
# The square of numbers example with function:
def square_of_num(num):
square_value = num * num
print(square_value)
square_of_num(2)
square_of_num(3)
square_of_num(5)
square_of_num(7)
square_of_num(11)
# `num` is the parameter, `2` (or `3`, `5`, `7` and `11`) is the argument.
# Functions can be defined to return nothing as the above or to
# return something.
# When we want to use the result of a function's operation(s) in
# another function, expression or a print statment, we need to return a value.
# If we try to print the result of the function above, we get a None value:
print(square_of_num(2))
# This is because, all functions in Python return something.
# If you do not explicitly return a value, a function will return None
# by default.
# To return a value, we return the result of the function's operations
# with a `return` statement. Not all functions must have a return statement.
# Parentheses aren't required for the return statement unless you need to
# enclose a complex expression that spans multiple lines.
def square_of_num(num):
square_value = num * num
return square_value
# Now we can use the result in a print statement and arithmetic expression
# like this:
print("The square of the second prime number 3 is:", square_of_num(3))
sum_of_squares = square_of_num(3) + square_of_num(4)
print(sum_of_squares)
# Since `square_value` is not useful for any purpose other than to hold a
# value which is immediately returned, we can remove that line and just
# return the square expression `num * num` to make our code more pythonic.
def square_of_num(num):
return num * num
# Try to keep your functions simple. Generally, your function should do one
# thing and do it well.
# This is known as the "Single-responsibility Principle". This is good practice
# because it makes it easier for you to test your code and find bugs.
#--------Documentating Functions with Docstrings-----------#
# You can use the `pass` statement to opt out of putting
# a body in a function or other block of code.
def documented_function(hi):
"""
This is how you document a function.
You put your documentation in Python documentation strings
(or docstrings) after the head of the function before anything else.
You use three double or single quotes at the beginning and at the end
of the string.
Line breaks and formatting are preserved. Indentation is optional.
You can specify arguments the function accepts and explain what the
function does in this docstring.
You can use help(name_of this_function) to see this documentation.
The returned string contains the expected arguments and what the
function returns.
"""
pass
print(help(documented_function))
# You will get a print of the function's definition head, your docstring and a
# `None` value at the end of the above print because the `help` function itself
# does not return a value.
# You can also use the __doc__ attribute given to you by Python to just print
# the content of your docstring.
print(documented_function.__doc__)
# The `square_of_num` function with documentation could look like this.
def square_of_num(num):
"""
square_of_num:
Takes in a number `num`, returns the square of num.
Args:
num: any number
Returns:
num * num: the square of num
"""
return num * num
print(square_of_num.__doc__)
#-----------Types of Functions-----------#
# There are three types of functions in Python:
# i) Built in functions like print(), type() and help()
# ii) User defined functions (UDF) like the ones we defined above.
# iii) Lambda functions (or Anonymous function). This will be covered when
# we get to data structures.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment