{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is a popular programming language. It was released in 1991." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is used for:\n", "\n", "web development (server-side),\n", "\n", "software development,\n", "\n", "mathematics,\n", "\n", "system scripting." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# What can Python do?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python can be used on a server to create web applications.\n", "\n", "Python can be used alongside software to create workflows.\n", "\n", "Python can connect to database systems. It can also read and modify files.\n", "\n", "Python can be used to handle big data and perform complex mathematics.\n", "\n", "Python can be used for rapid prototyping, or for production-ready software development." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Good to know" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The most recent major version of Python is Python 3, which we shall be using in this course. However, Python 2, although not being updated with anything other than security updates, is still quite popular." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Variables are containers for storing data values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has no command for declaring a variable.\n", "\n", "A variable is created the moment you first assign a value to it." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 5\n", "x" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'data'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = 'data'\n", "y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Data Types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In programming, data type is an important concept.\n", "\n", "Variables can store data of different types, and different types can do different things.\n", "\n", "Python has the following data types built-in by default, in these categories:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Text Type:\tstr\n", " \n", "Numeric Types:\tint, float, complex\n", " \n", "Sequence Types:\tlist, tuple, range\n", " \n", "Mapping Type:\tdict\n", " \n", "Set Types:\tset, frozenset\n", " \n", "Boolean Type:\tbool\n", " \n", "Binary Types:\tbytes, bytearray, memoryview\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Casting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to specify the data type of a variable, this can be done with casting." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = str(3)\n", "x" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = int(3)\n", "y" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z = float(3)\n", "z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Get the Type" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can get the data type of a variable with the type() function." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are three numeric types in Python:\n", "\n", "int\n", "\n", "float\n", "\n", "complex\n", "\n", "Variables of numeric types are created when you assign a value to them:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Int" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 1\n", "x" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-23121" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = -23121\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Float" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Float, or \"floating point number\" is a number, positive or negative, containing one or more decimals." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.1" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 1.1\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Float can also be scientific numbers with an \"e\" to indicate the power of 10." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1200.0" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 12E2\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Complex" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Complex numbers are written with a \"j\" as the imaginary part:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5j" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = 5j\n", "y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Type Conversion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can convert from one type to another with the int(), float(), and complex() methods" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 1\n", "x" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = float(x)\n", "y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings in python are surrounded by either single quotation marks, or double quotation marks.\n", "\n", "'hello' is the same as \"hello\".\n", "\n", "You can display a string literal with the print() function:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello\n" ] } ], "source": [ "print('hello')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Slicing Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can return a range of characters by using the slice syntax.\n", "\n", "Specify the start index and the end index, separated by a colon, to return a part of the string." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello, world!'" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"hello, world!\"\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "in python index is starting with 0, and for the end element you should put index+1, because it gets the one number before the specified index at the end part" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[0:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Slice To the End" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By leaving out the end index, the range will go to the end" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'llo, world!'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Modify Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has a set of built-in methods that you can use on strings." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Upper Case" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The upper() method returns the string in upper case:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello, world!'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"hello, world!\"\n", "a" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'HELLO, WORLD!'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.upper()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lower Case" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello'" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"Hello\"\n", "a" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.lower()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Remove Whitespace" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Whitespace is the space before and/or after the actual text, and very often you want to remove this space." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The strip() method removes any whitespace from the beginning or the end:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hello, world '" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ' hello, world '\n", "a" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello, world'" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.strip()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Replace String" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The replace() method replaces a string with another string:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 'hello'\n", "a" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'wello'" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.replace('h','w')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Split String" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The split() method returns a list where the text between the specified separator becomes the list items.\n", "\n", "The split() method splits the string into substrings if it finds instances of the separator:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello, world'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 'hello, world'\n", "a" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['hello', ' world']" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.split(',')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# String Concatenation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To concatenate, or combine, two strings you can use the + operator." ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'helloworld'" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 'hello'\n", "b = 'world'\n", "a+b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Booleans" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Booleans represent one of two values: True or False." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In programming you often need to know if an expression is True or False.\n", "\n", "You can evaluate any expression in Python, and get one of two answers, True or False.\n", "\n", "When you compare two values, the expression is evaluated and Python returns the Boolean answer:" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print(10 > 9)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "print(10 == 9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Operators" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Operators are used to perform operations on variables and values.\n", "\n", "In the example below, we use the + operator to add together two values:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15\n" ] } ], "source": [ "print(10+5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arithmetic operators are used with numeric values to perform common mathematical operations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " (+)\tAddition\tx + y\t\n", " \n", " (-)\tSubtraction\tx - y\t\n", " \n", " (*)\tMultiplication\tx * y\t\n", " \n", " /\tDivision x / y\n", " \n", " %\tModulus\tx % y\t\n", " \n", " **\tExponentiation\tx ** y\t\n", " \n", " //\tFloor division\tx // y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Comparison Operators" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comparison operators are used to compare two values:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ==\tEqual\tx == y\t\n", " !=\tNot equal\tx != y\t\n", " >\tGreater than\tx > y\t\n", " <\tLess than\tx < y\t\n", " >=\tGreater than or equal to\tx >= y\t\n", " <=\tLess than or equal to\tx <= y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are used to store multiple items in a single variable.\n", "\n", "Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.\n", "\n", "Lists are created using square brackets:" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ['a','b', 'c']\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# List Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "List items are ordered, changeable, and allow duplicate values.\n", "\n", "List items are indexed, the first item has index [0], the second item has index [1] etc.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ordered\n", "\n", "When we say that lists are ordered, it means that the items have a defined order, and that order will not change.\n", "\n", "If you add new items to a list, the new items will be placed at the end of the list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Access List Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "List items are indexed and you can access them by referring to the index number:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "please note that The first item in list has index 0." ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1,2,3,4,5,6]\n", "a" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Range of Indexes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can specify a range of indexes by specifying where to start and where to end the range.\n", "\n", "When specifying a range, the return value will be a new list with the specified items." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6, 7, 8]" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist = [1,2,3,4,5,6,7,8]\n", "mylist" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5]" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mylist[0:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Change Item Value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To change the value of a specific item, refer to the index number:" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 4]" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1,2,4]\n", "a" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[2] = 3\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Insert Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To insert a list item at a specified index, use the insert() method.\n", "\n", "The insert() method inserts an item at the specified index:" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple', 'orange']" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ['apple','orange']\n", "a" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "a.insert(2,'melon')" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple', 'orange', 'melon']" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Remove List Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The remove() method removes the specified item." ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "a.remove('melon')" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple', 'orange']" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remove Specified Index" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The pop() method removes the specified index.\n", "\n", "If you do not specify the index, the pop() method removes the last item." ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'orange'" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.pop(1)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple']" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Clear the List" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The clear() method empties the list.\n", "\n", "The list still remains, but it has no content." ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "a.clear()" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples are used to store multiple items in a single variable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A tuple is a collection which is ordered and unchangeable.\n", "\n", "Tuples are written with round brackets." ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('apple', 'orange', 'melon')" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = ('apple','orange','melon')\n", "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuple Items\n", "Tuple items are ordered, unchangeable, and allow duplicate values.\n", "\n", "Tuple items are indexed, the first item has index [0], the second item has index [1] etc.\n", "\n", "Ordered\n", "When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.\n", "\n", "Unchangeable\n", "Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Access Tuple Items\n", "\n", "You can access tuple items by referring to the index number, inside square brackets:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Range of Indexes\n", "\n", "You can specify a range of indexes by specifying where to start and where to end the range.\n", "\n", "When specifying a range, the return value will be a new tuple with the specified items." ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [], "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\")" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('cherry', 'orange', 'kiwi')" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thistuple[2:5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The search will start at index 2 (included) and end at index 5 (not included)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Change Tuple Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.\n", "\n", "But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple." ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('apple', 'kiwi', 'cherry')" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = (\"apple\", \"banana\", \"cherry\")\n", "y = list(x)\n", "y[1] = \"kiwi\"\n", "x = tuple(y)\n", "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Add Items\n", "\n", "Once a tuple is created, you cannot add items to it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Convert the tuple into a list, add \"orange\", and convert it back into a tuple:" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('apple', 'banana', 'cherry', 'orange')" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "y = list(thistuple)\n", "y.append(\"orange\")\n", "thistuple = tuple(y)\n", "thistuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries are used to store data values in key:value pairs.\n", "\n", "A dictionary is a collection which is unordered, changeable and does not allow duplicates.\n", "\n", "Dictionaries are written with curly brackets, and have keys and values:" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionary Items\n", "\n", "Dictionary items are unordered, changeable, and does not allow duplicates.\n", "\n", "Dictionary items are presented in key:value pairs, and can be referred to by using the key name." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print the \"brand\" value of the dictionary:" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ford'" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thisdict[\"brand\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unordered\n", "\n", "When we say that dictionaries are unordered, it means that the items does not have a defined order, you cannot refer to an item by using an index.\n", "\n", "Changeable\n", "\n", "Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.\n", "\n", "Duplicates Not Allowed\n", "\n", "Dictionaries cannot have two items with the same key:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary Length" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To determine how many items a dictionary has, use the len() function:" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(thisdict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Update Dictionary" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The update() method will update the dictionary with the items from the given argument.\n", "\n", "The argument must be a dictionary, or an iterable object with key:value pairs." ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [], "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict.update({\"year\": 2020})" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thisdict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Adding Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Adding an item to the dictionary is done by using a new index key and assigning a value to it:" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [], "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thisdict[\"color\"] = \"red\"\n", "thisdict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Removing Items" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The pop() method removes the item with the specified key name:" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'brand': 'Ford', 'year': 1964, 'color': 'red'}" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thisdict.pop(\"model\")\n", "thisdict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python If ... Else" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Equals: a == b\n", "\n", "Not Equals: a != b\n", "\n", "Less than: a < b\n", "\n", "Less than or equal to: a <= b\n", "\n", "Greater than: a > b\n", "\n", "Greater than or equal to: a >= b" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a and b are equal\n" ] } ], "source": [ "a = 33\n", "b = 33\n", "if b > a:\n", " print(\"b is greater than a\")\n", "elif a == b:\n", " print(\"a and b are equal\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The elif keyword is pythons way of saying \"if the previous conditions were not true, then try this condition\"." ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a is greater than b\n" ] } ], "source": [ "a = 200\n", "b = 33\n", "if b > a:\n", " print(\"b is greater than a\")\n", "elif a == b:\n", " print(\"a and b are equal\")\n", "else:\n", " print(\"a is greater than b\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The else keyword catches anything which isn't caught by the preceding conditions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python While Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has two primitive loop commands:\n", "\n", "while loops\n", "\n", "for loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The while Loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the while loop we can execute a set of statements as long as a condition is true." ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "i = 1\n", "while i < 6:\n", " print(i)\n", " i += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The break Statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the break statement we can stop the loop even if the while condition is true:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exit the loop when i is 3:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "i = 1\n", "while i < 6:\n", " print(i)\n", " if i == 3:\n", " break\n", " i += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The continue Statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the continue statement we can stop the current iteration, and continue with the next:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Continue to the next iteration if i is 3:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "4\n", "5\n", "6\n" ] } ], "source": [ "i = 0\n", "while i < 6:\n", " i += 1\n", " if i == 3:\n", " continue\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python For Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).\n", "\n", "This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.\n", "\n", "With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print each fruit in a fruit list:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n", "cherry\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The break Statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the break statement we can stop the loop before it has looped through all the items:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exit the loop when x is \"banana\":" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " print(x)\n", " if x == \"banana\":\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The range() Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To loop through a set of code a specified number of times, we can use the range() function,\n", "The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "for x in range(6):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the start parameter:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "for x in range(2, 6):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Else in For Loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The else keyword in a for loop specifies a block of code to be executed when the loop is finished:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print all numbers from 0 to 5, and print a message when the loop has ended:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "Finally finished!\n" ] } ], "source": [ "for x in range(6):\n", " print(x)\n", "else:\n", " print(\"Finally finished!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A function is a block of code which only runs when it is called.\n", "\n", "You can pass data, known as parameters, into a function.\n", "\n", "A function can return data as a result." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Creating a Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python a function is defined using the def keyword:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def my_function():\n", " print(\"Hello from a function\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello from a function\n" ] } ], "source": [ "my_function()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Information can be passed into functions as arguments.\n", "\n", "Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.\n", "\n", "The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "def my_function(fname):\n", " print(fname + \" William\")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Emil William\n", "Tobias William\n", "Linus William\n" ] } ], "source": [ "my_function(\"Emil\")\n", "my_function(\"Tobias\")\n", "my_function(\"Linus\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Parameters or Arguments?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A parameter is the variable listed inside the parentheses in the function definition.\n", "\n", "An argument is the value that is sent to the function when it is called." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def my_function(fname, lname):\n", " print(fname + \" \" + lname)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Emil Refsnes\n" ] } ], "source": [ "my_function(\"Emil\", \"Refsnes\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Arbitrary Arguments, *args" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.\n", "\n", "This way the function will receive a tuple of arguments, and can access the items accordingly:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If the number of arguments is unknown, add a * before the parameter name:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The youngest child is Linus\n" ] } ], "source": [ "def my_function(*kids):\n", " print(\"The youngest child is \" + kids[2])\n", "\n", "my_function(\"Emil\", \"Tobias\", \"Linus\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Default Parameter Value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following example shows how to use a default parameter value.\n", "\n", "If we call the function without argument, it uses the default value:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "def my_function(country = \"Norway\"):\n", " print(\"I am from \" + country)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am from Norway\n" ] } ], "source": [ "my_function()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am from Spain\n" ] } ], "source": [ "my_function('Spain')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Passing a List as an Argument" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.\n", "\n", "E.g. if you send a List as an argument, it will still be a List when it reaches the function:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "def my_function(food):\n", " for x in food:\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n", "cherry\n" ] } ], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "\n", "my_function(fruits)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Return Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To let a function return a value, use the return statement:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "def my_function(x):\n", " return 5 * x" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_function(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Lambda" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A lambda function is a small anonymous function.\n", "\n", "A lambda function can take any number of arguments, but can only have one expression." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Syntax\n", "\n", "lambda arguments : expression\n", "\n", "The expression is executed and the result is returned:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Add 10 to argument a, and return the result:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "x = lambda a : a + 10" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lambda functions can take any number of arguments:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiply argument a with argument b and return the result:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "x = lambda a, b : a * b" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x(2,3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.10" } }, "nbformat": 4, "nbformat_minor": 4 }