{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![title](header.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python as a Programming Language" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So far we've seen Python do some very simple things, that software like Excel could do just as well. What sets Python apart from other programming languages and software is it's ability to easily make automated programs quickly. Here we will look at the building blocks of writing programs, and think about how we can use them in a real environment." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A Deeper Look Into Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions are an integral part of Python - throughout your time with Python you will use many functions written by other people, and hopefully some you write yourself. A function can take in arguements as inputs, then performs a process, and then returns an output. Let's take a look at the pow() function to see what's going on:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "81\n" ] } ], "source": [ "print(pow(3,4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The pow() function takes in two arguements, and returns the first arguement to the power of the second. Let's take a look at how to write this function ourselves:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def myPow(a,b):\n", " return a ** b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The most important thing to remember here is the whitespace between the left margin and the second line; Python cares about indentations. In function definitions, we declare the name and arguements of a function, and then write the process, and what to return in an indented block. The names of the arguements don't matter - they are just dummy variables, used to give Python an example of what to do." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You might have noticed instead of printing you can just output the variable straight away:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 3\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What does this have to do with functions? The number one problem with function definitions is not knowing the difference between return and print. A function can only \"return\" one thing - when the function returns something, it ends, because the output has been reached. A function can \"print\" as many things as it wants - but won't treat these as outputs. This can lead to some interesting errors - let's look at what happens when we chain functions together written with print:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def myAdd(a,b):\n", " print(a + b)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "myAdd(3,5) #Nothing looks wrong here, right?" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] }, { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'NoneType' and 'int'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmyAdd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmyAdd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m#Oops\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m\u001b[0m in \u001b[0;36mmyAdd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mmyAdd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'NoneType' and 'int'" ] } ], "source": [ "myAdd(myAdd(3,5), 5) #Oops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With return, we don't have this problem:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def myAdd(a,b):\n", " return a + b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myAdd(myAdd(3,5),5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Outputs\" are helpful results of functions that actually mean something - \"Prints\" are just visuals to help you out!\n", "\n", "In short, if your function doesn't return anything, there's probably a problem!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## If Statements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes when writing a program we want Python to make choices for us depending on the input. If statements are usually used in a context with variables that change, for example functions. Let's look at the syntax with a simple function that tests if the input is 10 or not:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def isTen(number):\n", " \n", " if number == 10:\n", " \n", " return \"Yes!\"\n", " \n", " else:\n", " \n", " return \"No!\"\n", " \n", "print(isTen(10))\n", "print(isTen(5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some important things here - first off the indents again; if statements, like function definitions, need whitespace for Python to understand the code. Secondly, notice that when we construct the condition (number == 10), it's a double equals sign instead of a single. This is because the single equals is already used for setting variables. There are many conditionals we can use (for example: <, >, <=, >= are less than, greater than, less than or equal to, greater than or equal to) - make sure to check out the Python documentation [here](https://docs.python.org/3/) to see examples of more." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Not all questions are Yes or No - and Python has a way for us to deal with this - elif. For example, say we want to write a program that tells us if a number greater than 5 or less than or equal to 3:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def fiveOrThree(number):\n", " \n", " if number > 5:\n", " \n", " return \"This is a big number!\"\n", "\n", " elif number <= 3:\n", " \n", " return \"This is a small number!\"\n", " \n", " else:\n", " \n", " return \"I don't know how big this number is!\"\n", " \n", "print(fiveOrThree(2))\n", "print(fiveOrThree(5))\n", "print(fiveOrThree(6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another helpful conditional to use is in, usually used with lists:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fruit\n", "vegetables\n", "unknown\n" ] } ], "source": [ "fruits = [\"banana\", \"orange\", \"strawberry\"]\n", "vegetables = [\"carrot\", \"potato\", \"broccoli\"] # Note: not extensive lists of fruit or vegetables\n", "\n", "def fruitOrVeg(food):\n", " \n", " if food in fruits:\n", " \n", " return \"fruit\"\n", " \n", " if food in vegetables:\n", " \n", " return \"vegetables\"\n", " \n", " else:\n", " \n", " return \"unknown\"\n", " \n", "print(fruitOrVeg(\"banana\"))\n", "print(fruitOrVeg(\"carrot\"))\n", "print(fruitOrVeg(\"soup\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are two types of loop we'll look at here - the for loop and the while loop. Loops are used to do something simple over and over again to stop us from doing it. For example, say (for some reason) we don't know if the numbers 0 through 10 are bigger than 5 or smaller than 3. Using our function from earlier we can do the following:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for number in range(11): #range(11) gives us a list of the numbers 0-10\n", " \n", " print(fiveOrThree(number))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The for loop executes the indented code for every element in the list range(11)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While loops are slightly diffent - they check for a condition before executing the indented code. For example, a way of rewriting the code above would be:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number = 0\n", "while number <= 10:\n", " print(fiveOrThree(number))\n", " number += 1 #Shorthand way of saying number = number + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally with loops, sometimes we want to stop the loop prematurely to save time, or when we get what we want. Firstly, let's look at an example that finds the numbers from 2 to 20 that are not prime. A prime number is a number that's only divisible by itself or 1 - so any non-prime number will be divisible by a number from 2 to n. We just need to find what these are:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4 is not prime\n", "6 is not prime\n", "8 is not prime\n", "9 is not prime\n", "10 is not prime\n", "12 is not prime\n", "14 is not prime\n", "15 is not prime\n", "16 is not prime\n", "18 is not prime\n" ] } ], "source": [ "for number in range(2, 20):\n", " \n", " for x in range(2, number): #iterates from 2 to our number\n", " \n", " if number % x == 0: #this means our number is divisible f\n", " \n", " print(str(number) + \" is not prime\")\n", " break\n", "\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Can we do better than this? What if we want to find what the number's prime factors are? Here's some code that puts all we've learnt together:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number = 12847\n", "primes = []\n", "test = 2\n", "\n", "while True: #Sets up a loops that never ends unless we break it:\n", " \n", " if number == 1: #This will be clear later\n", " \n", " print(\"Decomposition found!\")\n", " print(primes)\n", " break #Finishes program\n", " \n", " elif number % test == 0: #If the number is divisible by the test number\n", " \n", " primes.append(test) #Adds the prime factor to the primes list\n", " number /= test #Shorthand for number = number / test\n", " \n", " else: \n", " test += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at this in more detail - we set up our number, an empty list for the primes, and the test number 2. We then set up an infinite while loop that will only end if we break it, then ask if the number has been fully decomposed into its factors. If this is the case, we print the decomposition and break out of the loop, ending the program. If this isn't the case, we check to see if our test number divides our number. If this happens, we add our test number to the list, and divide our number by the test number. If neither of these conditions are met, we just add 1 to the test number and try again. Eventually, the number will keep being divided by prime numbers and reach 1, at which point the program ends.\n", "\n", "At first glance this program may seem complicated, don't worry! Break it down into parts and see if you can understand each bit, then put it all together - once you've done that, try turning this into a function so we can input what \"number\" is.\n", "\n", "Similarly, if this program seems a bit wasteful - you're right! We could turn this into a function to generalise it more, or use better syntax in places to speed the program up. Programming is more of art than a science - there are many \"right answers\"!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Another Look At Methods" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We've already seen a method in the last guide, namely the append method. Let's talk about them a bit more to get comfortable with them, as we'll see them pop up everywhere.\n", "\n", "Strings in Python can act as lists - we can iterate over them using for loops, as well as perform some unique methods on them. For example, we can make a string into all upper case using the .upper() method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "string = \"hello python!\"\n", "print(string.upper())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, there are some methods for lists:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myList = [\"Tom\",\"Andy\",\"Pete\",\"Josh\"]\n", "\n", "print(myList.index(\"Andy\")) #Gives us the index of Andy\n", "print(myList.pop()) #Gives us the last element and removes it\n", "print(myList) #Gives us the list back, with the last element popped out." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries are our first real example of a data structure. They let us assign values to custom indexes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "HiPy = {\"location\": \"Liverpool University\", \"startDate\": 2016, \"language\": \"Python\"}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get our entries back out of the dictionary we index as if it were a list with custom indexes:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "HiPy[\"location\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries can help us manage data more intuitively at the price of using more memory. For example, if we wanted to store the marks of three students, we could use a list of lists, which is hard to read: " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "marks = [[90,86,70],[60,70,65],[90,40,60]]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or use a list of dictionaries:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "Adam = {\"maths\": 90, \"english\": 86, \"science\":70}\n", "Billy = {\"maths\": 60, \"english\": 70, \"science\":65}\n", "Chris = {\"maths\": 90, \"english\": 40, \"science\":60}\n", "\n", "students = [Adam, Billy, Chris]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can reference everything from the students list, or reference things directly from the students in a more intuitive way:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(Adam[\"maths\"])\n", "print(Billy[\"science\"])\n", "print(students[1][\"english\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Worked Example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's take a look at a program that outputs the first n numbers of the fibonacci sequence:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def fib(n):\n", " a = 1\n", " b = 1\n", " fibList = [1,1]\n", " \n", " while len(fibList) < n:\n", " b = a + b\n", " a = b - a #Shuffles the numbers around so we get the next pair\n", " fibList.append(b)\n", " \n", " return fibList\n", "\n", "print(fib(10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As with our prime example before, we set up our variables, then a while loop that checks to see if we've reached the nth fibonacci number yet. If it hasn't, we generate the next in the sequence and add it to the list. If it has, we return the list and finish the program. \n", "\n", "There are many ways of improving this program, including using indexing, or simultaneously declaring what a and b are in the while loop - however this code works well enough for now." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mini Project" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a long time, the number one programming challenge for programmers hoping to work at big tech companies was the \"FizzBuzz\" challenge. It involves making a program that given a number, returns Fizz if divisible by 3, and Buzz if divisible by 5, and FizzBuzz if divisible by both. Can you:\n", "\n", "* Make a function that does this?\n", "* Set up a for loop that runs this function on the numbers 1-100?\n", "* Using the map funciton, do the same as above, but without using a for loop?" ] } ], "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" } }, "nbformat": 4, "nbformat_minor": 2 }