python
play

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


  1. Python 1

  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

  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

  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

  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

  6. NumPy Math Functions and Variables • Here is the comprehensive list https://docs.scipy.org/doc/numpy/reference/routines.math.html 6

  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

  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 x 2 + 2xy + 3y 2 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

  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

  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 of 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

  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

  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

  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

  14. Logical Test • All the usual arithmetic comparisons may be made: Meaning Math Symbol Python Symbols Less than < < Greater than > > Less than or equal ≤ <= Greater than or equal ≥ >= Equals = == Not equal ≠ != • Logical operators: Meaning Python Symbols Logical AND and Logical OR or Logical NOT not 14

Recommend


More recommend