Python 1 Python Python is high-level programming language for - - PowerPoint PPT Presentation

python
SMART_READER_LITE
LIVE PREVIEW

Python 1 Python Python is high-level programming language for - - PowerPoint PPT Presentation

Python 1 Python Python is high-level programming language for general-purpose programming. Supports multiple programming paradigms, including object-oriented , imperative , functional programming, and procedural styles. Original


slide-1
SLIDE 1

Python

1

slide-2
SLIDE 2

Python

  • Python is high-level programming language for general-purpose programming.
  • Supports multiple programming paradigms, including object-oriented, imperative,

functional programming, and procedural styles.

  • Original implementation of Python provides only the language interpreter, but not

complier.

  • Created by Guido Van Rossum and first released in 1991.
  • There are two parallel branches of Python: “2.*” versions (latest 2.7.13)and “3.*”

versions (3.6.2 latest). “3.*” is not backward-compatible. Take a look at this https://docs.python.org/3/whatsnew/3.0.html

  • Available for all operating systems and supported by several software development

platforms.

  • Together with such packages as NumPy, SciPy and SymPy creates a powerful

environment for scientific computations.

  • Original Python implementation is free and open-source.

2

slide-3
SLIDE 3

Getting Python

  • We are going to work with Python 2.7
  • We also will use 3 additional packages: NumPy, SciPy and SymPy.
  • You can get everything separately:

https://www.python.org/downloads/, https://www.scipy.org/install.html, http://www.sympy.org/en/download.html

  • Or you can use some distributions which include all of the above, e.g.

Canopy (https://www.enthought.com/products/canopy/).

  • Pyhton with all required packages is also installed on our machines.

Just type “python” in the command line.

3

slide-4
SLIDE 4

Python Basics: Python as Calculator

  • The simplest way to use Python is as a command line (which sometimes referred to as

REPL https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop )

  • You can do basic arithmetic in the same way we did in MATLAB, but a few differences

should be noted:

  • Python does not print output of every operation automatically if the result is assigned to a

particular variable.

  • Use print statement or type the name of the variable instead.
  • Semicolon also has different meaning here.
  • Instead of ans special variable in MATLAB, underscore (_) is used in Python to access the result of

the last command.

  • Caret (^) operator has different meaning. Should use pow(x, y) instead.
  • Division of one integer by another will result in getting the integer part of the division (5/2=2). To

get fractional number either dividend or divisor should be fractional number as well (5.0/2=2.5 or 5/2.5=2.5).

  • Canopy provides more sophisticated shell called IPhython

(https://en.wikipedia.org/wiki/IPython)

4

slide-5
SLIDE 5

Python Basics: Importing Packages

  • Python itself implements very few mathematical functions.
  • If you need more, e.g. trigonometry or logarithms, you will need some additional

modules.

  • Modules are organized in packages. For example, NumPy is a package which contains

various modules implementing basic mathematical functions.

  • There are two ways to import packages:
  • import package_name [as package_alias] import alls the modules defined in the
  • package. Modules could be then accessed with package_name.module_name or

package_alias.module_name if alias was specified.

  • from package_name import module_name imports only specific module

module_name defined in the package package_name. Module could be then accessed without specifying package name. Also note that you can use wildcards for module_name to import multiple modules with a single command.

  • To see what modules are currently imported use sys.modules.keys().
  • See this link for more https://docs.python.org/2/tutorial/modules.html

5

slide-6
SLIDE 6

NumPy Math Functions and Variables

  • Here is the comprehensive list

https://docs.scipy.org/doc/numpy/reference/routines.math.html

6

slide-7
SLIDE 7

Python Basics: Defining Functions

  • To define the function, use the def keyword, tell the function name and what arguments you

want the function to accept, and then say what you want to do with those arguments. For example,

def g(x): … return x*x*x >>> g(2) 8 >>> g(2*3) 216

  • First, note the colon at the end of the line with def in it. This tells Python that there is more

function definition coming.

  • When you hit <Enter> then Python types the ellipses (. . . ) for you. These are to help you line up

your text properly, the point being that indentations are very important. We put in two leading spaces to indent the contents of our function definition, then told the function to “return” the cube of the argument.

  • When Python typed the next set of ellipses, we just hit <Enter> to end the function definition.

Thus, x represents the number where we want to evaluate the function, and the result of the evaluation is what appears on the return line.

  • After that g(2) evaluates to the cube of 2; g(2*3) evaluates to the cube of 6.
  • Also note that we are note specifying here a name for return parameter as we did in MATLAB.

Instead return keyword is used to pass results to calling function.

7

slide-8
SLIDE 8

Python Basics: Defining Functions

  • To define function with a single command (like anonymous functions

in MATLAB) use lambda expressions. The syntax is as follows:

<varibalename> = lambda <x1>,<x2>,…,<xn>: <expression>

  • So to define x2 + 2xy + 3y2 you should type f = lambda x,y:

x**2 + 2*x*y + 3*y**2

  • Also note that by default in Python you can not access variables

defined in your session from function definition (body). In MATLAB we can easily get the value of some session variable or modify it. But that is a bad practice, so it’s a good thing that Python prevents you from doing this.

8

slide-9
SLIDE 9

Python Basics: Data Types

  • As well as MATLAB, Python does dynamic typing, i.e. you do not specify data type of your variable

explicitly.

  • To know what data type your variable has use type(variable_name). To check whether

variable is of a given type use isinstance(variable_name, type_name).

  • Since Python is an object-oriented language, all data types are actually classes and variables are

instance (object) of these classes.

  • Python can support very sophisticated user-constructed data types, but the most basic data types

are: int (integer), long (integer with unlimited precision), float (double precision floating point number), complex (complex number), str (string), bool (boolean).

  • We can also use built-in functions like int(), float(), complex() and str() to convert

between types explicitly.

  • More on basic data types could be found here: https://docs.python.org/2/library/stdtypes.html
  • NumPy supports much more data types:

https://docs.scipy.org/doc/numpy/user/basics.types.html

9

slide-10
SLIDE 10

Arrays and Matrices

  • Python needs to be able to handle vectors and matrices with sophistication if it is to be

truly useful in mathematics, and as it happens, it can.

  • The most basic array structure in Python is called a list, and is simply an index ordered list
  • f objects. We will not discuss this much here, since it is of very little use mathematically.
  • Instead the suggestion is to use array structure of NumPy:

>>> v=array([1,2,3]) >>> u=array([-1,-2,-3]) >>> u+v array([0, 0, 0]) >>> u*v array([-1, -4, -9])

  • Check this out http://www.scipy-lectures.org/intro/numpy/array_object.html
  • Linear algebra routines performed on array structure:

https://docs.scipy.org/doc/numpy/reference/routines.linalg.html

10

slide-11
SLIDE 11

Arrays and Matrices

  • The array class can do structures of higher dimension as well, but it has one minor flaw, from a

mathematician’s point of view: it does not know about matrix multiplication.

  • We can make Python behave in a more natural fashion by using the matrix class.

>>> v=matrix([1,2,3]) >>> u=matrix([-1,-2,-3]) >>> v matrix([[1, 2, 3]]) >>> v.T matrix([[1], [2], [3]]) >>> u*v.T matrix([[-14]]) >>> u.T*v matrix([[-1, -2, -3], [-2, -4, -6], [-3, -6, -9]])

  • Check this out https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html
  • Note that linear algebra methods from the previous slide (the very last link) expect you to use

array strcture, not matrix. So, if you want to use any of them your choice may be array, not matrix.

11

slide-12
SLIDE 12

Primitive Types vs Reference Types

  • Take a look at this

http://pages.cs.wisc.edu/~bahls/cs302/PrimitiveVsReference.html and this http://www.python-course.eu/passing_arguments.php

12

slide-13
SLIDE 13

Flow Control: “if” statement

  • Meaning of “if” statement is exactly the same as in MATLAB. The syntax is also quite

similar:

if <condition_0>:

__Commands to be executed if <condition_0> is true

elif <condition_1>:

__Commands to be executed if <condition_1> is true

… elif <condition_N>:

__Commands to be executed if <condition_N> is true

Else:

__Commands to be executed if non of the <condition_0>, … , <condition_N> are true

  • Note that every logical test should be followed by the colon (:).
  • Note the keyword for alternative condition is elif, not elsif.
  • Note that there is no “end” keyword here. Separation of blocks of code is done with

indentations (red underscore (_) denotes a whitespace here)

13

slide-14
SLIDE 14

Logical Test

  • All the usual arithmetic comparisons may be made:
  • Logical operators:

Meaning Math Symbol Python Symbols Less than < < Greater than > > Less than or equal ≤ <= Greater than or equal ≥ >= Equals = == Not equal ≠ != Meaning Python Symbols Logical AND and Logical OR

  • r

Logical NOT not

14

slide-15
SLIDE 15

Flow Control: “for” loop

  • Again, the “for” loop has the same meaning as in MATLAB: iterates over given range of
  • variables. The syntax is as follows:

for <iterator> in <range>:

__Commands to be executed for every value from the <range>. Current value is accessed using <iterator> variable.

  • Note that Python’s syntax requires in keyword to be used instead of equality symbol (=)

as in MATLAB.

  • Note that the <range> is followed by the colon (:).
  • Note that there is no “end” keyword here. Separation of blocks of code is done with

indentations (red underscore (_) denotes a whitespace here).

  • Note that rather than always iterating over an arithmetic progression of numbers, or

giving the user the ability to define both the iteration step and halting condition, Python’s for statement iterates over the items of any sequence (a list or a string), in the

  • rder that they appear in the sequence.
  • You can interrupt loop execution with break statement.

15

slide-16
SLIDE 16

Flow Control: “while” loop

  • And again, the “while” loop has the same meaning as in MATLAB:

commands are executed until given condition is true.

while <condition>:

__ Commands to be executed while <condition> is true.

  • Note that the <condition> is followed by the colon (:).
  • Note that there is no “end” keyword here. Separation of blocks of

code is done with indentations (red underscore (_) denotes a whitespace here).

  • You can interrupt loop execution with break statement.

16

slide-17
SLIDE 17

Python Scripts

  • In the same way as we did in MATLAB, in Python we can store multiple commands to

script files. Then all the commands could be executed at once by calling that script.

  • Scripts files should have “.py” extension.
  • You can execute the script from the Windows or Linux command line by execute

command “python filename.py”, e.g. “python dosomething.py”.

  • You can execute the script from Python interactive shell by execution command

“execflie(‘filename’)”. Note that filename can be either a relative path (relative to your current working directory, where you were right before starting Python)

  • r an absolute path.
  • Note that when Python executes scripts from interactive shell, it ignores all the imports

done in current session. For example, if you imported NumPy in current interactive shell session, you need to have another import statement in your script in order to use NumPy functions, since Python doesn’t know what was happening in your session when it starts executing your script.

17

slide-18
SLIDE 18

Storing Functions

  • You can also store functions for future use in “.py” files.
  • Simply create a new file with arbitrary name (the only requirement is that the extension should

be “.py”) and define some functions (can be multiple functions) there using the syntax we learned.

  • To use these functions inside interactive shell or script you first need to import the file where the

functions are stored.

  • To do this you should use the same syntax as was used to import packages, e.g. you should

execute import myfuns as mf if you saved your functions in “myfuns.py”.

  • To use function you are supposed to follow the same rules as for using functions from imported

modules, e.g. mf.g(10) should be used to call function f defined in your “myfuns.py”, if you imported your file using the command from the above example.

  • Note that Python can import your functions only if you save them to the specific locations! The

easiest way is to store your function in the your current working directory. That’s where Python goes first to find your file. The other options could be found here https://docs.python.org/2/tutorial/modules.html#the-module-search-path

  • Also note that if you change your file after you imported it, Python will not see your changes and

you should reload your module manually with reload(mf) command.

18

slide-19
SLIDE 19

Indentations

  • Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only

delimiter is a colon (:) and the indentation of the code itself.

  • Code blocks are defined by their indentation. By "code block", we mean functions, “if” statements, “for” loops, “while” loops, and

so on. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. Every line of the particular block should have exactly the same indentation. It doesn't matter how large is it, just make sure it is the same for every line.

  • In this example, the function bodies (blocks) are indented with three spaces. The blocks of is statement are indented with 2

additional spaces. The block of the for loop is indented with 4 additional spaces.

def fib(n): 0 spaces print 'n =', n 3 spaces if n > 1: 3 spaces return n * fib(n - 1) 3+2=5 spaces else: 3 spaces print 'end of the line' 3+2=5 spaces return 1 3+2=5 spaces def foo(n): 0 spaces for i in range(10): 3 spaces print 'i = %d' % i 3+4=7 spaces

  • Check out some coding style standards suggested by official Python tutorial

https://docs.python.org/2/tutorial/controlflow.html#intermezzo-coding-style

19

slide-20
SLIDE 20

ICE #13

  • Create a function that implements bisection

algorithm for solving equations of the form f(x)=0.

  • Your functions should be stored in a separate

file.

  • Import your function from interactive shell and

try solving some equation.

  • Recall that you can define a function to test your

algorithm using lambda expressions, e.g. f1 = lambda x: x**2-4*x+5.

  • At the beginning of your function check whether

f(x1) or f(x2) are less than e. If yes, it means that x1 or x2 is the root of your equation and you’re done.

  • You can check your answer using on the

functions provided by NumPy https://docs.scipy.org/doc/scipy/reference/opti mize.nonlin.html

20

slide-21
SLIDE 21

Strings

  • As discussed in the data type page, Python can recognize strings entered using

any of three types of quotation marks. Once they are entered, they can be manipulated in fairly natural ways using operators that we would ordinarily consider as applying only to arithmetic.

>>> y="Yossarian said, " >>> twice='"I see everything twice!"' >>> y+twice 'Yossarian said, "I see everything twice!"' >>> twice*2 '"I see everything twice!""I see everything twice!“’

  • We see that we can define two strings as we did on the earlier page, but then

concatenate them using a + symbol: in Python, adding two strings concatenates

  • them. Multiplying a string by an integer concatenates that string to itself the

specified number of times. Do not try to multiply one string by another.

21

slide-22
SLIDE 22

Strings

  • Every string is actually an object in Python, with its own associated methods that can return properties of the string, or change the

string in various ways.

>>> len(y) 16 >>> y.find('said') 10 >>> y[10] 's' >>> Y=y.replace('said','shouted') >>> Y 'Yossarian shouted, ' >>> Y.upper() 'YOSSARIAN SHOUTED, ' >>> z=Y.lower() >>> z 'yossarian shouted, ' >>> z.capitalize() 'Yossarian shouted, '

  • More functions could be found here https://docs.python.org/2/library/string.html

22

slide-23
SLIDE 23

Formatting Output

  • We have seen that print statement prints a message to the console.
  • print statement expects you to provide string variable which is supposed to be displayed. But it also can

do formatting of that string for you, e.g. combining text and floating point numbers using given precision.

  • The syntax you can use for this purpose looks like this

print <string> % (variable1, variable2, … , variableN)

  • In your string you can use percent symbol together with a letter denoting type of your variable to insert

variable1, variable2, … , variableN values in the text, e.g. print ‘My whole number is %d. My fractional number is %f’ % (i, x). Note that order of variables specified after the string matters here.

  • Here is a good tutorial for this http://www.python-course.eu/python3_formatted_output.php
  • Note that this article applies to Python 3. The difference you should consider here is that Python 3 requires

you to surround everything which comes after print command with parenthes, i.e. print(‘My whole number is %d. My fractional number is %f’ % (i, x)). So just drop the parentheses and you will get a valid commands for Python 2.

  • To convert NumPy array to a string you can use array_str(array) function

https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html

23

slide-24
SLIDE 24

Reading and Writing Files

  • Python has some standard functions to read/write files of different types. You can

find some information here https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

  • We will consider the functions provided by NumPy for reading/writing tabular

data.

  • A fast and an easy way to read tabular data (e.g. CSV) is

numpy.loadtxt(filename). The function returns NumPy array variable containing the data stored in the file. More details are here https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

  • If you need more customizable function to read text file you can use this one

https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html

  • To write an array variable to a text file use numpy.savetxt(filename,

data). More details are here https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

24

slide-25
SLIDE 25

Optional Arguments

  • Python allows function arguments to have default values; if the function is called without the argument, the

argument gets its default value. Furthermore, arguments can be specified in any order by using named arguments.

  • For example, if you take a look at numpy.savetxt function specification (see the link from previous

slide), you would see something like this

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ‘)

  • This notation means that the function has just two required parameters (fname and X) that should go first

when you call the function and should be provided in the specified order (fnmae first and then X) without specifying the name of the parameter.

  • In turn, all other parameters (fmt, delimiter, newline, header, footer, comments) may be
  • mitted. If you do omit them, the default value will be used (which is provided in the function specification

right after equality symbol), e.g. '%.18e’ will be used for fmt parameter.

  • If you want another value to be used for fmt parameter you should explicitly specify the name of the

parameter and then specify value by separating the name and the value with equality sign. The order you use to specify optional parameters is arbitrary. For example, savetxt(fname, X, delimiter=‘|’, header=‘col1|col2’) or , savetxt(fname, X, header=‘col1|col2’, delimiter=‘|’) will produce the same result.

25

slide-26
SLIDE 26

ICE #14

  • The matrix form of the system of linear equations (Ax=b) is give by this matrix

http://www.math.wsu.edu/students/odykhovychnyi/M300/slides/09_Python/system.dat

  • Note that the delimiter used here is ‘|’.
  • Vector b is the last column. All preceding columns constitute matrix A.
  • Read the data into array variable (multidimensional).
  • Split the array variable into two new variables: matr – to represent matrix A; b – to represent a column-

vector b.

  • Solve the system (Ax=b) by using finding inverse of A and multiplying it by vector b (x=A-1b). You will need

this function https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html

  • Write your results to a file as a row-vector with coordinates separated by comma. You shouldn’t transpose x

vector for this purpose. The coordinates should be written as floating point numbers with 2 digits after in the fractional part.

  • Your script should work for matrices of arbitrary size. The only requirement is that number of variable is the

same as number of equations.

  • You can check your answer using NumPy function

https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html

26

slide-27
SLIDE 27

Plots

  • Matplotlib (http://matplotlib.org/) is a Python package that is included in SciPy and provides both 2-D and 3-D plotting routines.
  • pyplot module of Matplotlib provides a procedural interface to the matplotlib object-oriented plotting library. It is modeled closely after Matlab.

Therefore, the majority of plotting commands in pyplot have Matlab analogs with similar arguments.

  • To import pyplot module do: from matplotlib import pyplot as plt.
  • Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area,

decorates the plot with labels, etc.

X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C = np.cos(X) S = np.sin(X) plt.plot(X, C) plt.plot(X, S) plt.show()

  • Note that you can plot multiple graphs with a single plot(X1, Y1, X2, Y2,…) command in the same way as we did it in MATLAB. For every

graph you need to provide a pair of NumPy arrays representing x-values and y-values.

  • Note that pyplot does not clean figure automatically every time you call plot command as it happened in MATLAB. To clean current figure use

plt.cla() command.

  • plt.show() may have different effect depending on the mode you are using to run Python commands:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show

  • You can save the figure generated by pyplot to a file without actually showing it. You need plt.savefig(filename) command for that

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig

27

slide-28
SLIDE 28

Plots

  • Here are some examples how to customize line properties:
  • Comprehensive list of properties you can change could be found here:

http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties

  • To set x and y limits use plt.xlim(lower, upper) and plt.ylim(lower, upper)
  • To set x and y ticks use plt.xticks(xarray) and plt.yticks(yarray.
  • To set x and y axes labels use plt.xlabel(label) and plt.ylabel(label). To set

title use plt.title(title).

  • Matplotlib can also do some 3D plots https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
  • You can create multiple graphs on the same figure or even multiple figures at a time:

http://matplotlib.org/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes

  • Here are some nice tutorials with more examples: http://www.scipy-

lectures.org/intro/matplotlib/index.html and http://matplotlib.org/users/pyplot_tutorial.html

  • Here is a comprehensive pyplot reference: http://matplotlib.org/api/pyplot_api.html

28

slide-29
SLIDE 29

ICE #15

  • Define a function trapez(f, a, b, n, need_plot) that approximates definite integral

with trapezoid rule of f on [a, b] using n subintervals.

  • If need_plot is True,the function should also plot given function (size of the grid > n*10) and

dashed line connecting values of function at the endpoints of subintervals. The points should be highlighted using some points marker.

  • Define some function using lambda expression and test your function on some interval for some

value of n.

  • Compute integral of the function you defined using scipy.integrate.quad:

from scipy import integrate as intgr (val, err) = intgr.quad(f, a, b)

  • Compute integral using your trapez function using n = 2,4,6,…18, 20.
  • Plot an error of your computation (absolute value of the difference between the value computed

by trapez and the value computed by scipy.integrate.quad). Your x-axis should be the number of subintervals used.

  • Add meaningful labels to your graph.

29

slide-30
SLIDE 30

Speed

  • Read the book (“Essentials of Scientific Computing” by Prof. Cooper)

section 7.10.

30

slide-31
SLIDE 31

ICE #16

  • Modify the script you have created in ICE #15 so it will measure the

time required to approximate an integral using your trapez function.

  • To make it more illustrative use n= 10, 100, 100, …, 10^9
  • Plot the time results you have obtained.

31

slide-32
SLIDE 32

Classes

  • Read the book (“Essentials of Scientific Computing” by Prof. Cooper)

section 7.8.

32

slide-33
SLIDE 33

ICE #17

  • Define a class named “car”.
  • The class should have 3 attributes: color (string), position (number) and velocity

(number).

  • The class should have two methods: move and move_sec(secs).
  • move should update position of your car as if one second passed.
  • move_sec(secs) should update position of your car as if one secs seconds passed.
  • The suggestion is that you use meters for position and meters/seconds for velocity.
  • Create two variables (instances) of car class.
  • Define a loop that moves your cars by calling move_sec method with 0.5 input parameter.

The loop should run over 60 seconds.

  • The loop should stop when the cars are less than 10 meters from each other and display message

“Crash!”.

  • The loop should stop when the cars are more than 1000 meters from each other and display

message “Too far!”.

  • The loop should print current time in seconds and the positions of each car on for every iteration.

33

slide-34
SLIDE 34

Symbolics

  • Read the book (“Essentials of Scientific Computing” by Prof. Cooper)

section 7.12.

  • See http://docs.sympy.org/latest/tutorial/index.html
  • Complete documentation http://docs.sympy.org/latest/index.html

34

slide-35
SLIDE 35

References

  • Python Official Tutorials (https://docs.python.org/2/tutorial/)
  • SciPy Documentation (https://docs.scipy.org/doc/)
  • SciPy Lecture Notes (http://www.scipy-lectures.org/)
  • SymPy Tutorial (http://docs.sympy.org/latest/tutorial/index.html)
  • SymPy Documentation (http://docs.sympy.org/latest/index.html )
  • “Essentials of Scientific Computing” by Prof Cooper

(http://millenniummath.org/Computation/scientific_computing.pdf)

38