{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "# Quick Python Tutorial" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This tutorial should grow over time.\n", "Python has a number of types. You need to be familiar with some of them as a start, then you will learn about more as you go. Let's quickly investigate some of these here:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#Integers and floats" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "22\n", "33.33\n", "I am an integer/int: 22\n", "I am a float: 33.33\n" ] } ], "source": [ "#---------------------\n", "# Integers and floats:\n", "#---------------------\n", "# You can use Python as a calculator; and when you do, you are interacting with numbers that may have \n", "# \"int\" or \"float\" types. Let's print these, with a \"print\" statement.\n", "print 22 # an integer\n", "print 33.33 # a float\n", "\n", "# You can print more than an object with the same print statement, if you use an \",\" (coma) in between\n", "# (Hint: Both the integer 22 and the float 33.33 are 'objects' in the Pyathon language.\n", "# They are objects of type 'int' and type 'float,' respectively)\n", "print \"I am an integer/int:\", 22 # an integer\n", "print \"I am a float:\",33.33 # a float" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am an int division: 0\n", "I am an float division: 0.660066006601\n" ] } ], "source": [ "# You can perform operations on ints and floats, \n", "# but be cautious as to the difference between int division and float divison\n", "my_int= 22\n", "my_new_int=33\n", "my_float= 33.33\n", "print \"I am an int division:\", my_int/my_new_int\n", "print \"I am an float division:\", my_int/my_float\n", "# (Hint: We assigned the numbers to some variables above, more about 'assignment' below.\n", "# You can think about this just as storing something in another. It's like you put something in a box and \n", "# you are now just looking at the box from outside. Another metaphor is simply that you called each of the numbers a name\n", "# and can now interact with the numbers using these names.)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Strings" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n" ] } ], "source": [ "#--------\n", "# String:\n", "#--------\n", "# The string type is for characters like \"Hello world\". We can print this string:\n", "print \"Hello world\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n" ] } ], "source": [ "# The above is called a print statement. We can assign the string to a variable\n", "greeting = \"Hello world\"\n", "# We cann the word \"greeting\" a \"variable\" and the string \"Hello world\" a value. \n", "# What we did is \"assign\" the value \"Hello world\" to the variable \"greeting\".\n", "# The \"=\" is called an operator and we use it for \"assignment\". (This is important!)\n", "# We can now print \"grreting\"\n", "print greeting" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The type of the variable: \n", "The type of the value: 14\n" ] } ], "source": [ "# For another example, we can assign another string value to another variable:\n", "feeling=\"I love Python!\"\n", "# Since you love Python, it loves you back and so gives you a number of \"built-in\" functions to work with. \n", "# For more about these take a look here: https://docs.python.org/2/library/functions.html\n", "# For example, the \"type()\" function tells us about the type of an object. \n", "# Similarly, the \"len()\" function opertates in some objects, like strings, \n", "# and tells us about their length in characters:\n", "print \"The type of the variable: \", type(feeling)\n", "print \"The type of the value: \", len(feeling)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lists" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm an empty list []\n", "I'm list of string items ['Python', 'Lua', 'Java']\n", "I'm list of numbers [44, 11, 55]\n", "I'm list of string items and numbers ['Hello', 88, 4.0, 'Hey there!']\n" ] } ], "source": [ "#--------\n", "# List:\n", "#--------\n", "# A list is another Python data type where you can store and access your data with a lot of flexibility.\n", "# The list is a square-bracketed, comma-separated sequence of items.\n", "# So, to create a list, you use square brakets.\n", "# This is an empty list:\n", "my_first_list=[]\n", "print \"I'm an empty list\", my_first_list\n", "# Items in a list can be strings, or numbers, or a mixture\n", "words=[\"Python\", \"Lua\", \"Java\"]\n", "numbs= [44, 11, 55] \n", "words_and_numbs= [\"Hello\", 88, 4.0, \"Hey there!\"]\n", "print \"I'm list of string items\", words\n", "print \"I'm list of numbers\", numbs\n", "print \"I'm list of string items and numbers\", words_and_numbs\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "This is the first item in the list, and its index is zero Apple\n", "This is the last item in the list Facebook\n" ] } ], "source": [ "# Similar to a string, you can get the length of a list:\n", "tech_comp=[\"Apple\", \"Google\", \"Facebook\"]\n", "print len(tech_comp)\n", "# You can also slice from a list, using the bractets with an integer index.\n", "# Notice: we start from index \"zero\".\n", "print \"This is the first item in the list, and its index is zero\", tech_comp[0]\n", "# You can also access a list from the end, with a minus index\n", "print \"This is the last item in the list\", tech_comp[-1]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is my first tuple: ('Tiger', 'Lion', 'Monkey')\n" ] } ], "source": [ "# Tuples:\n", "#--------\n", "# A tuple is like a list, but its items are immutable/unchangeable.\n", "# The syntax is different in that the tuple employs the parathenses \"()\"\n", "my_animals_tuple=(\"Tiger\", \"Lion\", \"Monkey\")\n", "print \"This is my first tuple: \", my_tuple" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My list before changes: ['Tiger', 'Lion', 'Monkey']\n", "My list after changes: ['Goat', 'Lion', 'Monkey']\n" ] } ], "source": [ "# So you can change an item in a list, but not in a tuple:\n", "my_animals_list=[\"Tiger\", \"Lion\", \"Monkey\"]\n", "print \"My list before changes: \", my_animals_list\n", "my_animals_list[0]=\"Goat\"\n", "print \"My list after changes: \", my_animals_list\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This will give an error!\n" ] }, { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Trying to change this will give an error:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"This will give an error!\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"Goat\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ], "source": [ "# Trying to change this will give an error:\n", "print \"This will give an error!\"\n", "my_tuple[0]=\"Goat\"" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Dictionaries" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{777: 'Mary', 1111: 'John'}\n", "2\n", "Mary\n" ] } ], "source": [ "# A Ptthon dictionary is a \"mapping\" type. We map a \"key\" to a \"value\".\n", "# For example, we can map a \"student_id\" to the \"name\" of a student.\n", "# The sytax is simple: We use the curly braces, and delimit each key:value pair by the \"colon\"\n", "students={1111: \"John\", 777: \"Mary\"}\n", "print \"Printing the 'students' dict: \", students\n", "print \"The length of the 'students' dict is: \", len(students)\n", "# This is how you access the value of the key 777\n", "print print \"The value of the key 777 in the 'students' dict is: \", students[777]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value of the key 'CS' in the 'students' dict is: John\n" ] } ], "source": [ "# The keys don't have to be integers; they can be strings too. \n", "# Lets have keys represent the school of a student:\n", "students={\"CS\": \"John\", \"Business\": \"Mary\"}\n", "print \"The value of the key 'CS' in the 'students' dict is: \", students['CS']" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value of the key 'CS' in the 'students' dict is: ['John', 'Alex', 'Amanda']\n" ] } ], "source": [ "# A value in a Python dict can be a string, a list, another dict, etc.\n", "# So, if \"Alex\" and \"Amanda\" are also students in CS, then we can have the value for the key 'CS' as a list:\n", "students={\"CS\": [\"John\", \"Alex\", \"Amanda\"] , \"Business\": \"Mary\"}\n", "# And now when we print, we get all the students in CS as a full list:\n", "print \"The value of the key 'CS' in the 'students' dict is: \", students['CS']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Files" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Python is very efficient with files and text processing. Let's see how we open and interact with a file\n", "my_file=open(\"path_to_my_file\", \"r\").read() # Opens for reading and gets you the file content as a string\n", "my_file=open(\"path_to_my_file\", \"r\").readlines() # Opens for reading and gets you the file content as a list\n", "out_file=open(\"path_to_my_file\", \"w\") # Opens for writing\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Loops" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple \t--> is a fruit!\n", "strawberry \t--> is a fruit!\n", "grapes \t--> is a fruit!\n" ] } ], "source": [ "# Loops\n", "fruits=[\"apple\", \"strawberry\", \"grapes\"]\n", "for fruit in fruits:\n", " print fruit, \"\\t--> is a fruit!\"\n", "# \"\\t\" is the tab characters. Also be aware of \"\\n\", \"\\r\", and \"\\r\\n\" and how these work across different platforms." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dane !\n", "Hello Chris !\n", "Hello Lubna !\n", "Hello Nora !\n" ] } ], "source": [ "def greet(name):\n", " print \"Hello\", name, \"!\"\n", " \n", "# This is how you call the function:\n", "greet(\"Dane\")\n", "greet(\"Chris\")\n", "greet(\"Lubna\")\n", "greet(\"Nora\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'and': 4, 'learning.': 1, '(the': 1, 'family': 1, 'be': 1, 'other.': 1, 'experience,': 1, 'unknown.Artificial': 1, 'number': 1, 'numeric': 1, 'connections': 1, 'as': 1, 'brain)': 1, 'are': 4, 'learning': 1, 'in': 1, 'based': 1, 'tuned': 1, 'nets': 1, 'networks': 3, '(ANNs)': 1, 'functions': 1, 'depend': 1, 'capable': 1, 'nervous': 1, 'exchange': 1, 'generally': 2, 'approximate': 1, 'artificial': 1, 'machine': 1, 'to': 2, 'systems': 2, 'which': 1, 'between': 1, 'adaptive': 1, '\"neurons\"': 1, 'inputs': 2, 'used': 1, 'that': 2, 'models': 1, 'each': 1, 'animals,': 1, 'particular': 1, 'The': 1, 'estimate': 1, 'by': 1, 'a': 2, 'on': 2, 'central': 1, 'cognitive': 1, 'neural': 4, 'of': 5, 'inspired': 1, 'presented': 1, 'messages': 1, 'science,': 1, 'interconnected': 1, 'large': 1, 'weights': 1, 'can': 2, 'have': 1, 'In': 1, 'biological': 1, 'the': 1, 'or': 1, 'making': 1}\n" ] } ], "source": [ "# A function can \"return\" an object.\n", "# We provide an example here\n", "\n", "# text below is from https://en.wikipedia.org/wiki/Artificial_neural_network\n", "sentences=[\"In machine learning and cognitive science, artificial neural networks (ANNs)\\\n", " are a family of models inspired by biological neural networks (the central nervous systems of animals, \\\n", " in particular the brain) and are used to estimate or approximate functions that can depend on a large\\\n", " number of inputs and are generally unknown.\"\n", " \"Artificial neural networks are generally presented as systems of interconnected \\\"neurons\\\" which \\\n", " exchange messages between each other. The connections have numeric weights that can be tuned based \\\n", " on experience, making neural nets adaptive to inputs and capable of learning.\"]\n", "def get_dict(sentences):\n", " \"\"\"\n", " arguments:\n", " input: @sentences: a list of sentences\n", " returns: a dictionary of the words in the sentences.\n", " dict key is a word and value is word frequency\n", " \"\"\"\n", " word_freq={}\n", " for sent in sentences:\n", " words=sent.split()\n", " for w in words:\n", " if w in word_freq:\n", " word_freq[w]+=1\n", " else:\n", " word_freq[w]=1\n", " return word_freq\n", " \n", " \n", "my_word_freq_dict=get_dict(sentences)\n", "print my_word_freq_dict" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Here're are your keys with values > 2:\n", "****************************************\n", "and 4\n", "are 4\n", "networks 3\n", "neural 4\n", "of 5\n", "\n", "Here're are your keys with values > 1 and keys of more than 5 chars:\n", "**********************************************************************\n", "networks 3\n", "generally 2\n", "systems 2\n", "inputs 2\n", "neural 4\n" ] } ], "source": [ "# Here's the same function as above, but using python's \"defaultdict\"\n", "from collections import defaultdict\n", "sentences=[\"In machine learning and cognitive science, artificial neural networks (ANNs)\\\n", " are a family of models inspired by biological neural networks (the central nervous systems of animals, \\\n", " in particular the brain) and are used to estimate or approximate functions that can depend on a large\\\n", " number of inputs and are generally unknown.\"\n", " \"Artificial neural networks are generally presented as systems of interconnected \\\"neurons\\\" which \\\n", " exchange messages between each other. The connections have numeric weights that can be tuned based \\\n", " on experience, making neural nets adaptive to inputs and capable of learning.\"]\n", "\n", "def get_dict(sentences):\n", " \"\"\"\n", " arguments:\n", " input: @sentences: a list of sentences\n", " returns: a dictionary of the words in the sentences.\n", " dict key is a word and value is word frequency\n", " \"\"\"\n", " word_freq=defaultdict(int)\n", " for sent in sentences:\n", " words=sent.split()\n", " for w in words:\n", " word_freq[w]+=1\n", " return word_freq\n", " \n", "my_word_freq_dict=get_dict(sentences)\n", "# Let's print only keys with values > 2 this time\n", "print \"Here're are your keys with values > 2:\\n\", \"*\"*40\n", "for k in my_word_freq_dict:\n", " if my_word_freq_dict[k] > 2:\n", " print k, my_word_freq_dict[k]\n", "\n", "# Let's print only keys whose length > 5 (so keys that have at least 6 characters/letters) and values > 1 \n", "print \"\\nHere're are your keys with values > 1 and keys of more than 5 chars:\\n\", \"*\"*70\n", "for k in my_word_freq_dict:\n", " if my_word_freq_dict[k] > 1 and len(k) > 5:\n", " print k, my_word_freq_dict[k]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditionals" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is such a short list!\n" ] } ], "source": [ "fruits=[\"apple\", \"strawberry\", \"grapes\"]\n", "if len(fruits) < 10:\n", " print \"This is such a short list!\"" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I need an apple!\n" ] } ], "source": [ "fruits=[\"apple\", \"strawberry\", \"grapes\"]\n", "if \"apple\" not in fruits:\n", " print \"No apples?!\"\n", "else:\n", " print \"I need an apple!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# List Comprehension" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['s', 't', 'r', 'a', 'w', 'b', 'e', 'r', 'r', 'y']\n" ] } ], "source": [ "dessert=\"strawberry\"\n", "chars=[char for char in dessert]\n", "print chars" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['s', 't', 'r', 'w', 'b', 'r', 'r']\n" ] } ], "source": [ "# With a condition\n", "dessert=\"strawberry\"\n", "vowels=[\"a\", \"e\", \"y\"]\n", "chars=[char for char in dessert if char not in vowels]\n", "print chars" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "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 }