#!/usr/bin/env python # coding: utf-8 # In[1]: from IPython.core.display import HTML css_file = './stylesheets/custom.css' HTML(open(css_file, "r").read()) #
#
#

Introduction to Python

# #




#
# This tutorial is prepared by ACM/SIAM Student Chapter of King Abdullah University of Science and Technology (KAUST). #

# # Parts of this tutorial re-use Scientific Python lectures by Robert Johansson linsensed under Creative Commons Attribution 3.0. #

# # Presented on 26 February, 2017. #

# # **Prerequisites:** *No prerequisites.* #
# ## What is Python? # [Python](http://www.python.org/) is a **general-purpose**, high-level programming language. # # ### The main features: # - **Clarity and simplicity.** The language is human-readable, quick and easy to learn, minimalisitc. # - **Expressiveness.** Achieve the same with fewer lines of code. # In[2]: import this # ### Quick technical details: # - **Dynamically typed.** No need to define the type of variables, function arguments or return types. # - **Automatic memory management.** No need to explicitly allocate memory. Python will take care of this. # - **Interpreted.** The code is **not compiled**, but interpreted and executed on the fly by the Python interpreter. # # ### Advantages: # - Ease of programming. # - Minimal time on developing, debuggin, and maintain the projects. # - Powerful and well designed language: # - Modular, object-oriented, supports functional-style programming. # - Documentation tightly integrated with the code. # - Has a large, powerful, and well designed standard library, and numerous addiotional packages that can be installed literally in a few clicks. # # ### Disadvantages: # * Slowness compared to *C/C++* or *Fortran* *(but there are ways to speed it up!)*. # # # ## Why Python? # # # - A Large community of users makes it easy to find help and documentation. # # - An extensive ecosystem of scientific libraries and environments # - Numpy: http://numpy.scipy.org - Numerical Python # - SciPy: http://www.scipy.org - Scientific Python # - Matplotlib: http://www.matplotlib.org - graphics library # # - Great performance due to close integration with time-tested and highly optimized codes written in *C* and *Fortran*: BLAS, ATLAS BLAS, LAPACK, ARCPACK, ... # # - Good support for # * Parallel processing with processes and threads # * Interprocess communication (MPI) # * GPU computing (OpenCL and CUDA) # # - Readily available and suitable for use on high-performance computing clusters. # # - No license costs, no unnecessary use of research budget. # # ## Python program files # # * Python code is usually stored in text files with the file ending "`.py`": # # myprogram.py # # * Every line in a Python program file is assumed to be a Python statement, or part thereof. # # * The only exception is comment lines, which start with the character `#` (optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter. # # # * To run our Python program from the command line we use: # # $ python myprogram.py # # * On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned): # # #!/usr/bin/env python # # If we do, and if we additionally set the file script to be executable, we can run the program like this: # # $ myprogram.py # ## IPython notebooks # # This file - an IPython notebook - does not follow the standard pattern with Python code in a text file. Instead, an IPython notebook is stored as a file in the [JSON](http://en.wikipedia.org/wiki/JSON) format. The advantage is that we can mix formatted text, Python code and code output. It requires the IPython notebook server to run it though, and therefore isn't a stand-alone Python program as described above. Other than that, there is no difference between the Python code that goes into a program file or an IPython notebook. # #### Main features of the web application: (*from IPython docs*) # - In-browser editing for code, with automatic syntax highlighting, indentation, and tab completion/introspection. # - The ability to execute code from the browser, with the results of computations attached to the code which generated them. # - Displaying the result of computation using rich media representations, such as HTML, LaTeX, PNG, SVG, etc. For example, publication-quality figures rendered by the [matplotlib](http://matplotlib.org/) library, can be included inline. # - In-browser editing for rich text using the [Markdown](http://daringfireball.net/projects/markdown/syntax) markup language, which can provide commentary for the code, is not limited to plain text. # - The ability to easily include mathematical notation within markdown cells using LaTeX, and rendered natively by [MathJax](http://www.mathjax.org/). # First, let's see some useful shortcuts for [IPython notebook](http://www.ipython.org): # # - To run a cell click on it and hit *shift+enter*. # - To create a new cell below: *esc+b* # - To create a new cell above: *esc+a* # - To delete selected cells: *esc+d+d* # - Undo a cell deletion: *esc+z* # - Markdown cell to write text: *esc+m* # - Code cell: *esc+y* # - View all shortcuts: *esc+h* # IPython has a number of so-called [magic commands](http://ipython.org/ipython-doc/dev/interactive/magics.html). The following is an example. # In[3]: get_ipython().run_cell_magic('timeit', '', 'x = range(10000)\nsum(x)\n') # ## Modules # # Most of the functionality in Python is provided by *modules*. The Python Standard Library is a large collection of modules that provides *cross-platform* implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more. # # ### References # # * The Python Language Reference: http://docs.python.org/2/reference/index.html # * The Python Standard Library: http://docs.python.org/2/library/ # # To use a module in a Python program it first has to be imported. A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do: # In[4]: import math # This includes the whole module and makes it available for use later in the program. For example, we can do: # In[5]: import math x = math.cos(2 * math.pi) print(x) # Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don't need to use the prefix "`math.`" every time we use something from the `math` module: # In[6]: from math import * x = cos(2 * pi) print(x) # This pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the `import math` pattern. This would elminate potentially confusing problems with name space collisions. # # As a third alternative, we can chose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character `*`: # In[7]: from math import cos, pi x = cos(2 * pi) print(x) # It is also possible to rename the function or the imported module # In[8]: from math import cos as cos1 import math as ma x = cos1(2 * ma.pi) print(x) # ### Looking at what a module contains, and its documentation # # Once a module is imported, we can list the symbols it provides using the `dir` function: # In[9]: import math print(dir(math)) # And using the function `help` we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way). # In[10]: help(math.log) # In[11]: get_ipython().run_line_magic('pinfo', 'math.log') # In[12]: log(10) # Some very useful modules form the Python standard library are `os`, `sys`, `math`, `shutil`, `re`, `subprocess`, `multiprocessing`, `threading`. # # A complete lists of standard modules for Python 2 and Python 3 are available at http://docs.python.org/2/library/ and http://docs.python.org/3/library/, respectively. # --- # ### Exercise 1 # # Printing "Hello World!" is the standard first exercise in learning a new programming language. Use the command 'print' to do this. # In[ ]: # In[13]: # %load solutions/session1/hello-world.py print("Hello World!") # --- # # Language Synatax # ## Variables and types # # ### Symbol names # # Variable names in Python can contain alphanumerical characters `a-z`, `A-Z`, `0-9` and some special characters such as `_`. Normal variable names must start with a letter. # # By convension, variable names start with a lower-case letter, and Class names start with a capital letter. # # In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are: # # and, as, assert, break, class, continue, def, del, elif, else, except, # exec, finally, for, from, global, if, import, in, is, lambda, not, or, # pass, print, raise, return, try, while, with, yield # # Note: Be aware of the keyword `lambda`, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name. # # ### Assignment # # The assignment operator in Python is `=`. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one. # # Assigning a value to a new variable creates the variable: # In[14]: # variable assignments x = 1.0 my_variable = 12.2 # Although not explicitly specified, a variable do have a type associated with it. The type is derived form the value it was assigned. # In[15]: type(x) # If we assign a new value to a variable, its type can change. # In[16]: x = 1 # In[17]: type(x) # If we try to use a variable that has not yet been defined we get an `NameError`: # In[18]: try: print(y) except: print("y not defined") # ### Fundamental types # In[19]: # integers x = 1 type(x) # In[20]: # float x = 1.0 type(x) # In[21]: # boolean b1 = True b2 = False type(b1) # In[22]: # complex numbers: note the use of `j` to specify the imaginary part x = 1.0 - 1.0j type(x) # In[23]: print(x) # In[24]: print(x.real, x.imag) # ### Type utility functions # # The module `types` contains a number of type name definitions that can be used to test if variables are of certain types: # In[25]: import types # print all types defined in the `types` module print(dir(types)) # In[26]: x = 1.0 # check if the variable x is a float type(x) is float # In[27]: # check if the variable x is an int type(x) is int # We can also use the `isinstance` method for testing types of variables: # In[28]: isinstance(x, float) # ### Type casting # In[29]: x = 1.5 print(x, type(x)) # In[30]: x = int(x) print(x, type(x)) # In[31]: z = complex(x) print(z, type(z)) # In[32]: try: x = float(z) except: print("can't convert float to complex") # In[33]: x = abs(z) # but we can find the absolute value (length) of a complex number print(x) # ## Operators and comparisons # # Most operators and comparisons in Python work as one would expect: # # * Arithmetic operators `+`, `-`, `*`, `/`, `//` (integer division), '**' power # # In[34]: 1 + 2, 1 - 2, 1 * 2, 1 / 2, 3 // 2 # In[35]: 1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0 # In[36]: # Integer division of float numbers 3.0 // 2.0 # In[37]: # Note! The power operators in python isn't ^, but ** 2 ** 2 # * The boolean operators are spelled out as words `and`, `not`, `or`. # In[38]: True and False # In[39]: not False # In[40]: True or False # * Comparison operators `>`, `<`, `>=` (greater or equal), `<=` (less or equal), `==` equality, `!=` inequality, `is` identical. # In[41]: 2 > 1, 2 < 1 # In[42]: 2 > 2, 2 < 2 # In[43]: 2 >= 2, 2 <= 2 # In[44]: # equality [1,2] == [1,2] # In[45]: # inequality 1 != 1 # In[46]: # objects identical? l1 = [1,2] l2 = l1 l1 is l2 # --- # ### Exercise 2 # # Use Python to evaluate the following expression, for the given variables' values, to get the correct results and print the output # # `(5 * (a > b) + 2 * (a < b*4) ) / a * c` # # Note: you will need to use some variables casting # In[47]: a = 15 b = 5 c = 2.2 # expression evaluation here val = 0 print(val) # In[48]: # %load solutions/session1/operators.py a = 15 b = 5 c = 2.2 # expression evaluation here val = (5 * (a > b) + 2 * (a < b*4) ) / a * c print(val) # --- # ## Compound types: String, List, and Dict # # ### String # # Strings are the variable type that is used for storing text messages. # In[49]: s = "Hello world" type(s) # In[50]: # length of the string: the number of characters len(s) # In[51]: # replace a substring in a string with something else s2 = s.replace("world", "test") print(s2) # We can index a character in a string using `[]`: # In[52]: s[0] # **Heads up MATLAB users:** Indexing start at 0! # # We can extract a part of a string using the syntax `[start:stop]`, which extracts characters between index `start` and `stop`. # # **NOTE:** the `start` index is **included**, the `stop` is **excluded**. # In[53]: s[0:5] # If we omit either (or both) of `start` or `stop` from `[start:stop]`, the default is the beginning and the end of the string, respectively: # In[54]: s[:5] # In[55]: s[6:] # In[56]: s[:] # Negative indexing from the end of the string: # In[57]: s[:-2] # In[58]: s[-1], s[-2] # We can also define the step size using the syntax `[start:end:step]` (the default value for `step` is 1, as we saw above): # In[59]: s[::1] # In[60]: s[::2] # These technique is called *slicing*. Read more about the syntax here: http://docs.python.org/release/2.7.3/library/functions.html?highlight=slice#slice # ### String formatting # # Some examples of this subsection are brought from [http://docs.python.org/2/tutorial/inputoutput.html](http://docs.python.org/2/tutorial/inputoutput.html) # # Many operations can be performed over the strings in python. The following command shows the available string operations provided by str objects. # In[61]: print(dir(str)) # The following code shows an example of using the c-style formatting. More formatting specifiers can be found in a c language documentation. A good source: [http://www.cplusplus.com/reference/cstdio/printf/](http://www.cplusplus.com/reference/cstdio/printf/). # In[62]: import math print('The value of %5s is approximately %5.3f.' % ('PI', math.pi)) # The following code shows examples of using the `format` function to control the formatting of the input values to the string # In[63]: print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) # In[64]: print( 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible') ) # In[65]: print( 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg') ) # In[66]: import math print( 'The value of PI is approximately {0:.3f}.'.format(math.pi) ) # Python has a very rich set of functions for text processing. See for example http://docs.python.org/2/library/string.html for more information. # --- # ### Exercise 3 # # Use string built-in functions and sliding operation to perform the following over the text of `Hello world` # # * replace the letter `o` with `a`. (Hint: use the 'replace' built-in function in the string) # * Convert the first word to upper case letters. (Hint: use the 'upper' built-in function in the string) # * Convert the second word to lower case letters. (Hint: use the 'lower' built-in function in the string) # * Print out the character between the 4th and charachter before last inclusive. (Hint: use slicing operation) # # In[67]: s = "Hello world!" # In[68]: # %load solutions/session1/strings.py s = "Hello World" s = s.replace('o', 'a') print(s) s = s[:5].upper() + s[5:].lower() print(s) print(s[4:-1]) # --- # ### Lists # # Lists are very similar to strings, except that each element can be of any type. # # The syntax for creating lists in Python is `[...]`: # In[69]: l = [1,2,3,4] print(type(l)) print(l) # We can use the same slicing techniques to manipulate lists as we could use on strings: # In[70]: print(l) print(l[1:3]) print(l[::2]) # Elements in a list do not all have to be of the same type: # In[71]: l = [1, 'a', 1.0, 1-1j] print(l) # Python lists can be inhomogeneous and arbitrarily nested: # In[72]: nested_list = [1, [2, [3, [4, [5]]]]] print(nested_list) # Accessing elements in nested lists # In[73]: nl = [1, [2, 3, 4], [5, [6, 7, 8]]] print(nl) print(nl[0]) print(nl[1][1]) print(nl[2][1][2]) # Lists play a very important role in Python, and are for example used in loops and other flow control structures (discussed below). There are number of convenient functions for generating lists of various types, for example the `range` function: # In[74]: start = 10 stop = 30 step = 2 print(list(range(start, stop, step))) # In[75]: # convert a string to a list by type casting: s2 = list(s) print(s2) # In[76]: # sorting lists s2.sort() print(s2) # #### Adding, inserting, modifying, and removing elements from lists # In[77]: # create a new empty list l = [] # add an elements using `append` l.append("A") l.append("d") l.append("d") print(l) # In[78]: l[1:3] = ["d", "d"] print(l) # Remove an element at a specific location using `del`: # In[79]: del l[0] print(l) # Using operators with lists # In[80]: l1 = [1, 2, 3] + [4, 5, 6] print(l1) l2 = [1, 2, 3] * 2 print(l2) # See `help(list)` for more details, or read the online documentation # --- # ### Exercise 4 # # Perform the following list operations and print the final output # # * Create a list of the odd numbers between 4 and 16 # * Replace the last element of the list with a list of even numbers between 3 and 9 # * At the list in the last element, change the value of the element before last with `-1` # * Remove elements between the 2nd and 3rd inclusive # * Insert a the string `Hello` after the first element # # In[ ]: # In[81]: # %load solutions/session1/lists.py l = list(range(5, 17, 2)) print(l) l[-1] = list(range(4, 10, 2)) print(l) l[-1][-2] = -1 print(l) del l[1:3] print(l) l.insert(1, "Hello") print(l) # --- # ### Dictionaries # # Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is `{key1 : value1, ...}`: # In[82]: params = {"parameter1" : 1.0, "parameter2" : 2.0, "parameter3" : 3.0, 1: 4.0, (5, 'ho'): 'hi'} print(type(params)) print(params) # In[83]: print("parameter1 = " + str(params["parameter1"])) print("parameter2 = " + str(params["parameter2"])) print("parameter3 = " + str(params["parameter3"])) # In[84]: params["parameter1"] = "A" params["parameter2"] = "B" # add a new entry params["parameter4"] = "D" print("parameter1 = " + str(params["parameter1"])) print("parameter2 = " + str(params["parameter2"])) print("parameter3 = " + str(params["parameter3"])) print("parameter4 = " + str(params["parameter4"])) print("'key 1' = " + str(params[1])) print("'key (5, 'ho')' = " + str(params[(5, 'ho')])) # In[85]: del params["parameter2"] print(params) # --- # ### Exercise 5 # # Create a dictionary that uses a string "first last" name of the person as a key and his/her corresponding age as a value for the following list of people # # * John Smith 30 # * Ahmad Said 22 # * Sara John 2 # # Perform the following updates to the dictionary # # * Increase the age of John by one year # * Add a new person named Ahmad Ahmad with age 19 # * remove Sara from the dictionary # # In[ ]: # In[86]: # %load solutions/session1/dicts.py d = dict() d["John Smith"] = 30 d["Ahmad Said"] = 22 d["Sara John"] = 2 print(d) d["John Smith"] += 1 d["Ahmad Ahmad"] = 19 del d["Sara John"] print(d) # --- # ## Control Flow # ### Conditional statements: if, elif, else # # The Python syntax for conditional execution of code use the keywords `if`, `elif` (else if), `else`: # In[87]: statement1 = False statement2 = False if statement1: print("statement1 is True") elif statement2: print("statement2 is True") else: print("statement1 and statement2 are False") # For the first time, here we encounted a peculiar and unusual aspect of the Python programming language: Program blocks are defined by their indentation level. # # Compare to the equivalent C code: # # if (statement1) # { # printf("statement1 is True\n"); # } # else if (statement2) # { # printf("statement2 is True\n"); # } # else # { # printf("statement1 and statement2 are False\n"); # } # # In C blocks are defined by the enclosing curly brakets `{` and `}`. And the level of indentation (white space before the code statements) does not matter (completely optional). # # But in Python, the extent of a code block is defined by the indentation level (usually a tab or say four white spaces). This means that we have to be careful to indent our code correctly, or else we will get syntax errors. # # **Examples:** # In[88]: statement1 = False if statement1: print("printed if statement1 is True") print("still inside the if block") # In[89]: if statement1: print("printed if statement1 is True") print("now outside the if block") # In[90]: # a compact way for using the if statement a = 2 if statement1 else 4 print("a =", a) # In[91]: name = 'john' if name in ['jed', 'john']: print("We have Jed or John") num = 1 if num in [1, 2]: print("We have 1 or 2") # ## Loops # # In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. The basic syntax is: # # # **`for` loops**: # In[92]: for x in [1,2,3]: print(x) # The `for` loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the `for` loop. For example: # In[93]: for x in range(4): # by default range start at 0 print(x) # Note: `range(4)` does not include 4 ! # In[94]: for x in range(-3,3): print(x) # In[95]: for word in ["scientific", "computing", "with", "python"]: print(word) # To iterate over key-value pairs of a dictionary: # In[96]: for key, value in params.items(): print(str(key) + " : " + str(value)) # Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the `enumerate` function for this: # In[97]: for idx, x in enumerate(range(-3,3)): print(idx, x) # **`while` loops**: # In[98]: i = 0 while i < 5: print(i) i = i + 1 print("done") # Note that the `print("done")` statement is not part of the `while` loop body because of the difference in indentation. # --- # ### Exercise 6 # # Loop through the following list of words and create a dictionary according to the following rules: # # - Add a word to the dictionary if its length is greater than 2. # - Word lengths should be the keys, lists of words with corresponding lengths should be the values. In other words, for every key in the dictionary its value is a list of words with the same length as the key. # In[99]: words = ["Aerial", "Affect", "Agile", "Agriculture", "Animal", "Attract", "Audubon", "Backyard", "Barrier", "Beak", "Bill", "Birdbath", "Branch", "Breed", "Buzzard", "The", "On", "Upper", "Not", "What", "Linked", "Up", "In", "A", "lol"] # In[ ]: # In[100]: # %load solutions/session1/control_flow.py d = dict() for w in words: n = len(w) if n > 2: if n not in d: d[n] = [] d[n].append(w) for i, l in d.items(): print(i, l) # --- # ## Functions # # A function in Python is defined using the keyword `def`, followed by a function name, a signature within parentheses `()`, and a colon `:`. The following code, with one additional level of indentation, is the function body. # In[101]: def func0(): print("test") # In[102]: func0() # Optionally, but highly recommended, we can define a so called "docstring", which is a description of the functions purpose and behaivor. The docstring should follow directly after the function definition, before the code in the function body. # In[103]: def func1(s): # Print a string 's' and tell how many characters it has print(s + " has " + str(len(s)) + " characters") return 1, 2, 3 # In[104]: help(func1) # In[105]: func1("test") # We can return multiple values from a function using tuples (see above): # In[106]: def powers(x): # Return a few powers of x. return x ** 2, x ** 3, x ** 4 # In[107]: powers(3) # In[108]: x2, x3, _ = powers(3) print(x3) # ### Default argument and keyword arguments # # In a definition of a function, we can give default values to the arguments the function takes: # In[109]: def myfunc(x, p=2, debug=False): if debug: print("evaluating myfunc for x = " + str(x) + " using exponent p = " + str(p)) return x**p # If we don't provide a value of the `debug` argument when calling the the function `myfunc` it defaults to the value provided in the function definition: # In[110]: myfunc(5) # In[111]: myfunc(5, debug=True) # If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called *keyword* arguments, and is often very useful in functions that takes a lot of optional arguments. # In[112]: myfunc(p=3, debug=True, x=7) # ## Further reading # # * http://www.python.org - The official web page of the Python programming language. # * http://www.python.org/dev/peps/pep-0008 - Style guide for Python programming. Highly recommended. # * http://www.greenteapress.com/thinkpython/ - A free book on Python programming. # * [Python Essential Reference](http://www.amazon.com/Python-Essential-Reference-4th-Edition/dp/0672329786) - A good reference book on Python programming. # *Copyright 2017, ACM/SIAM Student Chapter of King Abdullah University of Science and Technology*