{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#Functions\n", "\n", "##Introduction to Functions\n", "\n", "This lecture will consist of explaining what a function is in Python and how to create one. Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.\n", "\n", "**So what is a function?**\n", "\n", "Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.\n", "\n", "On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.\n", "\n", "Functions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design (we will dive much deeper into the ideas of design when we learn about Object Oriented Programming)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## def Statements\n", "\n", "Let's see how to build out a function's syntax in Python. It has the following form:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def name_of_function(arg1,arg2):\n", " '''\n", " This is where the function's Document String (doc-string) goes\n", " '''\n", " # Do stuff here\n", " #return desired result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a [built-in function in Python](https://docs.python.org/2/library/functions.html) (such as len).\n", "\n", "Next come a pair of parenthesis with a number of arguments separated by a comma. These arguments are the inputs for your function. You'll be able to use these inputs in your function and reference them. After this you put a colon.\n", "\n", "Now here is the important step, you must indent to begin the code inside your function correctly. Python makes use of *whitespace* to organize code. Lots of other programing languages do not do this, so keep that in mind.\n", "\n", "Next you'll see the doc-string, this is where you write a basic description of the function. Using iPython and iPython Notebooks, you'll be ab;e to read these doc-strings by pressing Shift+Tab after a function name. Doc strings are not necessary for simple functions, but its good practice to put them in so you or other people can easily understand the code you write.\n", "\n", "After all this you begin writing the code you wish to execute.\n", "\n", "The best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Example 1: A simple print 'hello' function" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def say_hello():\n", " print 'hello'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Call the function" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello\n" ] } ], "source": [ "say_hello()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Example 2: A simple greeting function\n", "Let's write a function that greets people with their name." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def greeting(name):\n", " print 'Hello %s' %name" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Jose\n" ] } ], "source": [ "greeting('Jose')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using return\n", "Let's see some example that use a return statement. return allows a function to *return* a result that can then be stored as a variable, or used in whatever manner a user wants.\n", "\n", "### Example 3: Addition function" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def add_num(num1,num2):\n", " return num1+num2" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add_num(4,5)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Can also save as variable due to return\n", "result = add_num(4,5)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n" ] } ], "source": [ "print result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What happens if we input two strings?" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "onetwo\n" ] } ], "source": [ "print add_num('one','two')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.\n", "\n", "Lets also start using *break*,*continue*, and *pass* statements in our code. We introduced these during the while lecture." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Finally lets go over a full example of creating a function to check if a number is prime ( a common interview exercise).\n", "\n", "We know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def is_prime(num):\n", " '''\n", " Naive method of checking for primes. \n", " '''\n", " for n in range(2,num):\n", " if num % n == 0:\n", " print 'not prime'\n", " break\n", " else: # If never mod zero, then prime\n", " print 'prime'" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "not prime\n" ] } ], "source": [ "is_prime(16)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note how we break the code after the print statement! We can actually improve this by only checking to the square root of the target number, also we can disregard all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import math\n", "\n", "def is_prime(num):\n", " '''\n", " Better method of checking for primes. \n", " '''\n", " if num % 2 == 0 and num > 2: \n", " return False\n", " for i in range(3, int(math.sqrt(num)) + 1, 2):\n", " if num % i == 0:\n", " return False\n", " return True" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "is_prime(14)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great! You should now have a basic understanding of creating your own functions to save yourself from repeatedly writing code!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }