{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Built-in functions\n", "\n", "Python provides a set of functions already built-in. You are already very familiar with one of them:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Here print is the function\n", "# Within parentheses we pass ONE parameter, the string with the message\n", "print(\"Oh yeah, I am a function! I print things on the screen\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# The print function can take more than one parameter\n", "# For example below we pass three strings as parameters\n", "name = \"Panos\"\n", "print(\"Hi\", name, \"How are you\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You have already encountered `len`, `sum`, `max`, and `min`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "nums = [3, 41, 12, 9, 74, 15]\n", "\n", "# len() takes as a parameter a string (and returns its length in characters)\n", "# or a list/set/dictionary/... (and returns the number of elements)\n", "print(\"Length:\", len(nums))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# max() / min() takes as a parameter a *list* and returns \n", "# the maximum or minimum element\n", "print(\"Max:\", max(nums))\n", "print(\"Min:\", min(nums))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# sum() gets as input a list of numbers and returns their sum\n", "print(\"Sum:\", sum(nums))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- We have also used various type conversion functions, such as `set`, `list`, and `tuple`. We can also do type conversions with `int`, `float`, and `str`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Convert to integer\n", "int(3.7)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Convert to float\n", "float(2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Convert to float <- also works with strings!\n", "float('6.8')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Convert to string \n", "str(233)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- And, we used `type` to find out the type of a given variable. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Type for a float\n", "x = 1.99\n", "type(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Type for a string \n", "y = 'abc'\n", "type(y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Type for a list\n", "z = ['a', True, 3]\n", "type(z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Type for an element of a list\n", "type(z[1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Type for all elements of a list \n", "[type(i) for i in z]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- In a variety of contexts, we also used the `range` and `sorted` functions. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "list(range(-10,10,2))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# sorted() has a list as input and returns the list with the elements sorted\n", "sorted([5,23,3,77,9,12])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You may also have seen the `round` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "round(3.14159, 2) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The list at https://docs.python.org/3/library/functions.html contains all the built-in functions of Python. \n", "**As a general rule of thumb, avoid using these bult-in function names as variable names.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions from Libraries\n", "\n", "We can also add more functions by `import`-ing libraries. For example, we can import the `math` library. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# math.fabs returns the absolute value\n", "math.fabs(-2345)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# math.fabs takes the factorial\n", "math.factorial(5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "math.factorial(5) == 5*4*3*2*1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another commonly used library is the `random` library that returns random numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import random" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": true }, "outputs": [], "source": [ "# random.random() returns random values from 0 to 1\n", "for i in range(10):\n", " print(round(random.random(), 3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "#random.choice() can be used to select items from a list\n", "for i in range(5):\n", " print(random.choice(['a','b','c','d']))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And, you have seen the `time` package" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import time\n", "time.sleep(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### User Defined Functions\n", "\n", "\n", "** See also Examples 18, 19, 20, and 21 from Learn Python the Hard Way **\n", "\n", "Functions assign a name to a block of code the way that variables assign names to bits of data. This seemingly benign naming of things is incredibly powerful; allowing one to reuse common functionality over and over. Well-tested functions form building blocks for large, complex systems. As you progress through Python, you'll find yourself using powerful functions defined in some of Python's vast libraries of code. \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Function definitions begin with the `def` keyword, followed by the name you wish to assign to a function. Following this name are parentheses, `( )`, containing zero or more variable names, those values that are passed into the function. There is then a colon, followed by a code block defining the actions of the function:\n", "\n", " def function_name(function_input)\n", " ... function actions ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Printing \"Hi\"\n", "\n", "Let's start by looking at a function that performs a set of steps." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def print_hi():\n", " print(\"hi!\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "for i in range(10):\n", " print_hi()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Of course, most functions have also one or more _parameters_. For example, the function below will accept the name as a parameter, and then print out the message \"HI _name_\", where _name_ is the value of the parameter that we pass to the function. The function will also convert the _name_ into uppercase:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def hi_you(name):\n", " '''\n", " This function takes as input/parameter the variable name\n", " And then prints in the screen the message \n", " HI ! \n", " where is the content of the name variable converted to uppercase\n", " '''\n", " print(\"HI\", name.upper())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "names = ['Panos', 'Peter', 'Kylie', 'Jennifer', 'Elena']\n", "for n in names:\n", " hi_you(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Let's modify the `hi_you` to take as input a *list* of names and print out all of them " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def hi_you_all(list_of_names):\n", " '''\n", " This function takes as input/parameter list_of_names\n", " And then prints in the screen the message \n", " HI ! \n", " for all the names in the list_of_names.\n", " \n", " The paramater 'names' is a list of strings, with every string\n", " being a name that we want to print out\n", " '''\n", " for name in list_of_names:\n", " print(\"HI\", name.upper(), \"!\")\n", " # Alternatively, we could reuse the function hi_you(name)\n", " # hi_you(name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "names = ['Panos', 'Peter', 'Kylie', 'Jennifer', 'Elena']\n", "hi_you_all(names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### The `return` statement \n", "\n", "Example of computing a math function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# The functions are often designed to **return** the\n", "# result of a computation/operation\n", "def square(num):\n", " squared = num*num\n", " return squared" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = square(3) # notice that square RETURNS a value that \n", " # we store in variable x \n", " # this is in contrast to hi_you and hi_you_all\n", " # that just printed out messages on the screen\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "for i in range(15):\n", " print(f\"The square of {i} is {square(i)}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the function `square` has a special keyword `return`. The argument to return is passed to whatever piece of code is calling the function. In this case, the square of the number that was input. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Solving the quadratic equation\n", "\n", "Here is another example of a function, for solving the quadratic equation \n", "$$ a*x^2 + b*x + c = 0$$\n", "Recall that the quadratic formula is:\n", "$$ x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import math\n", "\n", "a = 4\n", "b = -32\n", "c = 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# We want to solve the quadratic equation a*x^2 + b*x + c = 0 \n", "\n", "# We have two solutions:\n", "s1 = (-b + math.sqrt(b**2 - 4*a*c) ) / (2*a) \n", "s2 = (-b - math.sqrt(b**2 - 4*a*c) ) / (2*a) \n", "\n", "print(f\"Solution 1: {s1:.3f}\")\n", "print(f\"Solution 2: {s2:.3f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see an example of how a function can return \"multivalued\" results using tuples/lists." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def quadratic(a,b,c) : # Function takes a,b,c as input\n", "\n", " s1 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) \n", " s2 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) \n", " \n", " return s1, s2 # Note that we can return multiple things\n", " # The \"return\" value does not have to be a single value\n", " # A function can even return a list, tuple, dictionary, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Observe that the function returns a tuple with s1 and s2\n", "sol = quadratic(a,b,c)\n", "\n", "print(\"Solutions:\", sol )\n", "print(\"Solutions:\", sol[0] )\n", "print(\"Solutions:\", sol[1] )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# If we want, we can even assign a value to each item returned, like so:\n", "sol1, sol2 = quadratic(a,b,c)\n", "\n", "print(\"Solutions:\", sol1 )\n", "print(\"Solutions:\", sol2 )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# We can even check that the value of the discriminant\n", "# is positive before returning a result\n", "\n", "def quadratic(a,b,c):\n", " \n", " discr = b**2 - 4*a*c\n", " if discr < 0: # We will not compute \n", " return None # \"None\" is a special value, meaning \"nothing\"\n", " \n", " s1 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) \n", " s2 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) \n", " \n", " return s1, s2 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "quadratic(6,1,9)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "quadratic(6,27,9)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "## A COMMON MISTAKE:\n", "# Using multiple return statements\n", "# Why? After we execute the first return, \n", "# we do not execute anything below that\n", "\n", "def quadratic_s1_only(a, b, c):\n", " \n", " discr = b**2 - 4*a*c\n", " if discr < 0: # We will not compute \n", " return None # \"None\" is a special value, meaning \"nothing\"\n", " \n", " \n", " s1 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) \n", " s2 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) \n", " \n", " return s1 # solution 1 \n", " return s2 # solution 2, BUT this will never be executed" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "quadratic_s1_only(a, b, c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Example function: Cleaning up a string\n", "We can use the `string` library to get a list of all letters by typing `string.ascii_letters`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# This code prints all the letters in the alphabet\n", "import string\n", "string.ascii_letters" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# this function takes as input a phone string variable\n", "# and removes anything that is not a letter or space\n", "\n", "def clean(text):\n", " result = \"\"\n", " letters = string.ascii_letters + \" \"\n", " for c in text: \n", " if c in letters:\n", " result = result + c\n", " return result " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "p = \"(800) 555-1214 Phone number\"\n", "print(clean(p))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercises\n", "\n", "* Write a function `in_range` that checks if a number `n` is within a given range `(a,b)` and returns True or False. The function takes n, a, and b as parameters.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Your function here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** \n", "def in_range(n, a, b):\n", " if n>a and n\n", "def dedup(l):\n", " return sorted(list(set(l)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Write a function to test whether two strings are equal, ignoring capitalization." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Your function here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer**: \n", "def are_equal(s1,s2):\n", " if s1.lower() == s2.lower():\n", " return True\n", " else:\n", " return False \n", "are_equal(\"potato\", \"PoTATo\")\n", "are_equal(\"potato\", \"PoTAToes\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Write a function that generates a random password with `n` letters. The value `n` should be a parameter." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# This code generates one random letter\n", "import random\n", "random.choice(string.ascii_letters)\n", "\n", "# Your function here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Answer:** \n", "def random_letter():\n", " return random.choice(string.ascii_letters)\n", "def random_password(n):\n", " password = ''\n", " for i in range(0,n):\n", " password+= random_letter()\n", " return password " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.6" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 1 }