Python How To : Functions and Exceptions

Python PictureHere I’ll go over a bunch more on Python. If you haven’t seen Part 1 of the Python How To Program Tutorial, read it first.

In this article I’ll cover functions, exception handling and general file i/o. I’ve read your comments, and yes I will be providing a bunch of Python sample programs and videos. They may already be done actually. Check the right side bar on this site where it says categories, click on Python How to. That will display every Python article. Well on with the article.

Python Functions

You create functions so that you can encapsulate your code (Make it look neat). Inside a function you can store code that can be easily called from elsewhere in your program. You define functions in Python not by surrounding the code with curly braces {}, like other languages, but instead through indenting. Here is an example function:

def bigIterator():

listIterator = [1,2,3,4,5] # Note on how to create a small list
listIterator[:] = range(1,201) # Creating a list from 1 to 200
for i in listIterator: print(i)

This function is named bigIterator. The braces () that follow the name of the function, is where you would put the names of arguments that are passed to your function. More on that in a minute. Each function definition, also begins with the word def.

In Python you then indent (normally 4 spaces) each line that follows the first line of the function. This function doesn’t return a value, but instead just prints a list of numbers from 1 to 200. More can be found on lists in Python How To Part 2.

I can call for this function, by just typing bigIterator(), any where else in the program code.

Python Function Arguments

Here I’ll show you how to create a function that excepts values (arguments) and performs certain calculations on those values. Here is an example:

def multiplyTwo(firstNum=1, secondNum=2, *args):

print(firstNum * 2)
print(secondNum * 2)
for i in args: print(i * 2, end = ‘\n’)
return “Everything is Fine”

If you called the above program with multiplyTwo(1, 2, 3, 4, 5, 6) it would print out the numbers 1 thru six multiplied by 2, on individual lines. If different arguments were passed this function will print out:

  • The numbers 2 and 4, if no arguments are passed to it
  • 2 multiplied times an infinite number of arguments that are passed

What is *args, you may ask? When you don’t know how many arguments may be passed you define *args as the last argument for a function. Those values sent beyond what you were expecting, will be saved in a tuple named args.

I performed another protective measure here by defining default values for the variables named firstNum and secondNum. I did that by assigning that default with the equals sign (=). If nothing is passed, the default is used. Otherwise the value passed is used.

At the end of the function I returned a value to the caller of this function. I’m just forwarding a string with the statement “Everything is Fine”. If I called the function multiplyTwo like this print(multiplyTwo()). The output to the screen would be:

2
4
Everything is Fine

That’s pretty much all there is to regular old functions in Python. I’ll cover functions or methods in Object Oriented Python very soon.

Python Exceptions

Let’s say I didn’t define default values in the function above. What would have happened if I then called multiplyTwo()? I would have received an error message like this:

TypeError: multiplyTwo() takes at least 2 positional arguments (0 given)

TypeError is the name of the exception that is being raised. The line of text that proceeds the colon, is the error message itself.

I could catch this error with an exception handler this way:

try:

multiplyTwo()

except TypeError as e:

print(e)

else:
…rest of the code…

The above lines of code will catch the specific error TypeError. The variable e is the error message I defined above. So basically what this does is if the wrond arguments are sent, it prints out the error message to the screen. I could print anything out of course in the print statement however.

But, what happens if an error is triggered that I didn’t account for? You can protect against that by just using a blank except like this:

except:

Now every error will be caught. You can resolve each error differently, by listing multiple except lines for each possible error and then use the blank except: line as a catchall for those you have missed.

Raising Exceptions

You could also choose to throw your own error messages with the raise command. The raise command excepts the name of the exception followed by the error message you want displayed like this:

raise TypeError(‘Enter at least 2 values for multiplyTwo to work’)
To finish off this explanation on how to handle errors in Python, I’ll go over the finally option. While it is not needed finally can be used when you definitely want certain code to be executed when the try statement is entered. It works like this:

def divideNStuff(x,y):

try:
divResult = x / y
except ZeroDivisionError:
print (“division by zero!”)
else:
print (str(x) + ” divided by ” + str(y) + ” equals ” + str(divResult))
finally:
print (“We made it to the end”)

This function protects itself from a ZeroDivisionError. Whether the exception or else statement is ever executed, you can be sure that the finally statement will be executed.

That’s All Folks

You’ve learned a bunch about Python over the last few articles, but after I go over Object Oriented Programming, Regular Expressions and File I/O, you’ll be ready for more. By more I mean some useful real Python Programs.

If you have any questions leave them below.

Till Next Time

Think Tank

Leave a Reply

Your email address will not be published.

Google+