LEARN PYTHON: CHAPTER FOUR

L

In the last chapter, we spoke about a broad set of topics within the programming world specifically Python. In this chapter I’m going to show you how to write functions, how they work, and why you should use them. Then I will also talk about loops, why and when you should use them, and finally we can speak about some Python built-ins (built-in functions)

When it comes to writing code, things become quite repetitive, and without any experience, you may often find yourself writing the same bit of code, over and over again. It is fairly common to run into this issue, and sometimes the problem you’re trying to find a solution.

Enter the Function

Functions

Functions allow us to complete a few things when it comes to our code, while on the surface it doesn’t appear so important, when you start writing more complex scripts and programs, you’ll want to start using these techniques:

  • Modularity
  • Organization
  • Less repetition

Your first scripts can possibly look something like this, and that is OKAY! It is a great lesson, and the more you practice, the more you find out why you’re doing it.

#!/usr/bin/python3

"""
A simple script, no functions and a small loop that loops through an array of values. how to extract values from those array's.
"""

# create an array of values to be used in the function
myArray = ['dog', 'cat', 'mouse', 'horse', 'cow', 'pig']

# print out the array
print(myArray)

# loop through the array
for arr in myArray:
    # print out all of the elements in the array
    print(arr)

# print elements individually without a loop
print(myArray[0])
print(myArray[1])
print(myArray[2])
print(myArray[3])
print(myArray[4])
print(myArray[5])

# print the entire array 
print(myArray)

# print a string with formatting and concatenation as well as array elements
print(myArray[0] + f" is mans best friend.")
print(myArray[1] + f" is a {myArray[2]}'s worst enemy.")
print(myArray[2] + f" is a {myArray[1]}'s best friend.")
print(myArray[3] + f" is a mans worst enemy.")
print(myArray[4] + f" is yummy to a human.")
print(myArray[5] + f" is yummy to some humans.")

# Same thing can happen, even without concatenation, but with formatting
print(f"{myArray[0]} is mans best friend.")
print(f"{myArray[1]} is a {myArray[2]}'s worst enemy.")
print(f"{myArray[2]} is a {myArray[1]}'s best friend.")
print(f"{myArray[3]} is a mans worst enemy.")
print(f"{myArray[4]} is yummy to a human.")
print(f"{myArray[5]} is yummy to some humans.")

# print only 3 elements in the array using slicing 
print(myArray[0:3])

# print only the first element, and first 2 characters in the array using slicing
print(myArray[0][:2])

# the first 5 elements
print(myArray[:5])

# print the last 5 elements
print(myArray[-5:])

# print the last 5 elements in reverse
print(myArray[-5:][::-1])

# subtrack 5 from the end of the array and print the remaining element
print(myArray[:-5])

You can see how this is far too repetitious, and it can be really disorganized. Not only that, the code really only performs a small amount of work and there isn’t much real-world usefulness this code can possibly do for us…. Of course, we’re only just learning.

BREAKING THINGS DOWN

You may have noticed that this script will run, even without having a def main() function our code still runs. In the example above, we created an array with a default set of values, and from there we perform a loop that loops through the entire array and prints out each element in that array. When you use a for loop, the value arr becomes a variable on its own and assigned the value currently at the index being iterated over. You can then print these individual values

Things can become very repetitive, and this is where functions come in handy. Of course, functions also play a bigger role, but for now lets use it to simplify some of the code we have already written. You can copy and paste this, or you can type it out, that is entirely up to you.

#!/usr/bin/python3

"""
A Simple script with function that loops and returns
"""

def animalTypeChecker(myArray):
    '''
    make cat do something
    '''
    meow = 'woooof!'
    if 'dog' in myArray:
        return meow

    return myArray

def myLoopingFunction(myArray):
    for arr in myArray:
        return myArray

def main():
    # create an array of values to be used in the function
    myArray = ['dog', 'cat', 'mouse', 'horse', 'cow', 'pig']

    myRunningFunction = myLoopingFunction(myArray)

    for i in myRunningFunction:
        try:
            if 'dog' in i:
                check_animal = animalTypeChecker(i)
                print(check_animal)
            else:
                print(i)
        except Exception as e:
            print(e)

main()

As you can see, we create three functions, animalTypeChecker myLoopingFunction a main() function, which helps us keep our code organized. Inside of our main function we define an array and give it a few index values. We then call our function and store it inside of a variable myRunningFunction we then loop through all of the values inside of myRunningFunction with a for loop.

When we use for i in myRunningFunction we are declaring i as a variable that gets assigned the index of each value within myRunningFunction. The reason that myRunningFunction has any values at all is because we first pass in myArray into myLoopingFunction with myRunningFunction = myLoopingFunction(myArray) and then, we loop through each of those values and return each value back to the variable that is calling the function, this lets us then loop through each of those values within myRunningFunction, and perform additional tests, like in check_animal = animalTypeChecker(i) where we check if there is a dog, and return an entirely new string back which will print the ‘wooof!’ instead of ‘dog’

Functions are great, they simplify your code, reduce the amount of code required to perform something repetitive, and keep your code organized, modular, and reusable. Things like multiplication can be simplified, instead of having to manually write things out, we can just define our tasks as needed.

#!/usr/bin/python3

def multiplier(x, y):
    return x * y

def divider(x, y):
  return x / y 

def add(x, y):
  return x + y
  
def subtract(x, y):
  return x - y

def main():
    x = input('Enter num to be multiplied: ')
    y = input('Enter num to be multiplied: ')
    multiply = multiplier(x, y) 
    division = divider(x, y)
    adder = add(x, y)
    subtractor = subtract(x, y) 
    print(multiply, division, adder, subtractor) 
    
main() 

Our code we wrote does a very simple thing, it takes the users input and stores it into the variables x and y, then we call our multiplier function and store the results returned from it into our variable multiply, we can then print this value, or use it wherever we need it. The same thing happens for all of the functions listed.

In conclusion, functions can turn a complicated mess of code into very simple, easy to understand and reusable code. The next chapter we will be developing a small program that lets us use our newly found skills in the real world, so that we can retain this knowledge and understand more of the WHY we are coding, rather than just aimlessly writing HELLO WORLD examples for years on end.

Until next time.

rob

Entrepreneur at heart, currently working on a social media site – I do DevOps consulting on my off-time so if you have some contract work you can contact me here. I currently work as a Site Reliability Engineer; My past work as a DevOps Engineer for a self-driving car company. When I'm not in front of a computer – I am at the gym or at the beach.

Social

ADVERTISEMENT

Don't miss out!

Don't miss out! Sign up to be notified when new content drops.