Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Python - Tutorial Python is a very simple language, and has a very straightforward syntax. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. The Python interpreter and the extensive standard library are freely available. This tutorial introduces many of Python’s most noteworthy features, and will give you a good idea of the language’s flavor and style. How to Start Python Invoking the Interpreter The Python interpreter is usually installed as /usr/local/bin/python. The path /usr/local/bin is put in the Unix shell’s search. This makes it possible to start python by typing the command 1 python Invocation of a Script The most common use case is, of course, a simple invocation of a script: 1 p y t h o n m y s c r i p t . py When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing −i before the script: 1 p y t h o n − i m y s c r i p t . py Hello, World! The simplest directive in Python is the print directive - it simply prints out a line. To print a string, just write: 1 p r i n t ’ H e l l o , World ! ’ Comments in Python start with the hash character # and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. Indentation Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. For example: x = 1 i f x == 1 : 3 # indented four spaces 4 print ’x i s 1. ’ 1 2 1 Variables and Types Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object. This tutorial will go over a few basic types of variables. Number Python supports two types of numbers - integers and floating point numbers. To define an integer, use the following syntax: 1 myint = 7 To define a floating point number, you may use one of the following notations: 1 2 myfloat = 7.0 myfloat = f l o a t (7) Strings Strings are defined either with a single quote or a double quotes. 1 2 mystring = ’ h e l l o ’ mystring = " h e l l o " The difference between the two is that using double quotes makes it easy to include apostrophes (whereas these would terminate the string if using single quotes) 1 m y s t r i n g = "Don ’ t w o r r y a b o u t a p o s t r o p h e s " Simple operators can be executed on numbers and strings: 1 2 3 4 5 6 one = 1 two = 2 t h r e e = one + two hello = " hello " world = " world " h e l l o w o r l d = h e l l o + " " + world Assignments can be done on more than one variable "simultaneously" on the same line like this 1 a, b = 3, 4 Mixing operators between numbers and strings is not supported: 1 2 # T h i s w i l l n o t work ! p r i n t one + two + h e l l o 2 Lists Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Here is an example of how to build a list. 1 2 3 4 5 6 7 8 mylist = [] m y l i s t . append ( 1 ) m y l i s t . append ( 2 ) m y l i s t . append ( 3 ) print ( mylist [ 0 ] ) # prints print ( mylist [ 1 ] ) # prints print ( mylist [ 2 ] ) # prints mylist2 = range (1 ,20 ,2) # 1 2 3 range ( s t a r t i n g p o i n t , endpoint , s t e p s i z e ) Accessing an index which does not exist generates an exception (an error). 1 2 mylist = [1 ,2 ,3] print ( mylist [10]) To find out the length of a list, just use 1 len ( mylist ) Basic Operators This section explains how to use basic operators in Python. Arithmetic Operators Just as any other programming languages, the addition, subtraction, multiplication, and division operators can be used with numbers. 1 number = 1 + 2 ∗ 3 / 4 . 0 Try to predict what the answer will be. Does python follow order of operations? Another operator available is the modulo % operator, which returns the integer remainder of the division. dividend % divisor = remainder 1 r e m a i n d e r = 11 % 3 Using two multiplication symbols makes a power relationship. 1 2 s q u a r e d = 7 ∗∗ 2 cubed = 2 ∗∗ 3 Using Operators with Strings Python supports concatenating strings using the addition operator: 1 h e l l o w o r l d = " h e l l o " + " " + " world " Python also supports multiplying strings to form a string with a repeating sequence: 1 l o t s o f h e l l o s = " h e l l o " ∗ 10 3 Using Operators with Lists Lists can be joined with the addition operators: even_numbers = [ 2 , 4 , 6 , 8 ] odd_numbers = [ 1 , 3 , 5 , 7 ] 3 a l l _ n u m b e r s = odd_numbers + even_numbers 1 2 Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator: 1 print [1 ,2 ,3] ∗ 3 String Formatting Python uses C-style string formatting to create new, formatted strings. The % operator is used to format a set of variables enclosed in a ’tuple’ (a fixed size list), together with a format string, which contains normal text together with ’argument specifiers’, special symbols like %s (strings) and %d (integers). Let’s say you have a variable called name with your user name in it, and you would then like to print out a greeting to that user. # T h i s p r i n t s o u t " H e l l o , John ! " name = " John " 3 p r i n t " H e l l o , %s ! " % name 1 2 To use two or more argument specifiers, use a tuple (parentheses): # T h i s p r i n t s o u t " John i s 23 y e a r s o l d . " name = " John " 3 age = 23 4 p r i n t "%s i s %d y e a r s o l d . " % ( name , age ) 1 2 Any object which is not a string can be formatted using the %s operator as well. For example: # This p r i n t s out : A l i s t : [ 1 , 2 , 3 ] mylist = [1 ,2 ,3] 3 p r i n t "A l i s t : %s " % m y l i s t 1 2 Here are some basic argument specifiers you should know: • %s - String (or any object with a string representation, like numbers) • %d - Integers • %f - Floating point numbers • %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. • %x/%X - Integers in hex representation (lowercase/uppercase) 4 Conditions Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated. For example: x = 2 2 p r i n t x == 2 # p r i n t s o u t True 3 p r i n t x == 3 # p r i n t s o u t F a l s e 4 p r i n t x < 3 # p r i n t s o u t True 1 Notice that variable assignment is done using a single equals operator =, whereas comparison between two variables is done using the double equals operator ==. The "not equals" operator is marked as !=. Boolean Operators The and and or boolean operators allow building complex boolean expressions, for example: name = " John " 2 age = 23 3 i f name == " John " and age == 2 3 : 4 p r i n t " Your name i s John , and you a r e a l s o 23 y e a r s o l d . " 1 5 6 7 i f name == " John " or name == " R i c k " : p r i n t " Your name i s e i t h e r John o r R i c k . " The in Operator The in operator could be used to check if a specified object exists within an iterable object container, such as a list: 1 2 i f name i n [ " John " , " R i c k " ] : p r i n t " Your name i s e i t h e r John o r R i c k . " Here is an example for using Python’s statement if using code blocks: 1 2 3 4 5 6 7 8 9 10 11 12 i f <s t a t e m e n t i s t r u e >: <do s o m e t h i n g > .... .... e l i f <a n o t h e r s t a t e m e n t i s t r u e >: # e l s e i f <do s o m e t h i n g e l s e > .... .... else : <do a n o t h e r t h i n g > .... .... 5 For example: 1 2 3 4 5 x = 2 i f x == 2 : p r i n t " x e q u a l s two ! " else : p r i n t " x d o e s n o t e q u a l t o two . " A statement is evaluated as true if one of the following is correct: 1. The True boolean variable is given, or calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered "empty" is passed. Here are some examples for objects which are considered as empty: 1. An empty string: "" 2. An empty list: [] 3. The number zero: 0 4. The false boolean variable: False The is Operator Unlike the double equals operator ==, the is operator does not match the values of the variables, but the instances themselves. For example: x = [1 ,2 ,3] 2 y = [1 ,2 ,3] 3 p r i n t x == y # P r i n t s o u t True 4 p r i n t x i s y # P r i n t s out F a l s e 1 The not Operator Using not before a boolean expression inverts it: 1 2 p r i n t not F a l s e # P r i n t s o u t True p r i n t ( not F a l s e ) == ( F a l s e ) # P r i n t s o u t F a l s e 6 Loops There are two types of loops in Python, for and while. The for Loop for loops iterate over a given sequence. Here is an example: 1 2 3 primes = [2 , 3 , 5 , 7] for prime in primes : print prime for loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. Note that the xrange function is zero based. 1 2 3 4 5 6 7 8 9 # P r i n t s o u t t h e numbers 0 , 1 , 2 , 3 , 4 for x in xrange ( 5 ) : # or range (5) print x # P r i n t s out 3 ,4 ,5 fo r x in xrange (3 , 6 ) : # or range (3 , 6) print x # P r i n t s out 3 ,5 ,7 f o r x in xrange (3 , 8 , 2 ) : # or range (3 , 8 , 2) print x while Loops while loops repeat as long as a certain boolean condition is met. For example: # P r i n t s out 0 ,1 ,2 ,3 ,4 count = 0 3 while count < 5: 4 print count 5 c o u n t += 1 # T h i s i s t h e same a s c o u n t = c o u n t + 1 1 2 break and continue Statements break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the for or while statement. A few examples: 1 2 3 4 5 6 7 # P r i n t s out 0 ,1 ,2 ,3 ,4 count = 0 w h i l e True : print count c o u n t += 1 i f c o u n t >= 5 : break 8 9 # P r i n t s o u t o n l y odd numbers − 1 , 3 , 5 , 7 , 9 7 10 11 12 13 14 for x in xrange (10): # Check i f x i s e v e n i f x % 2 == 0 : continue print x Functions What are Functions? Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code. How do you Write Functions in Python? Functions in python are defined using the block keyword def, followed with the function’s name as the block’s name. For example: 1 2 def m y _ f u n c t i o n ( ) : p r i n t " H e l l o From My F u n c t i o n ! " Functions may also receive arguments (variables passed from the caller to the function). For example: 1 2 def m y _ f u n c t i o n _ w i t h _ a r g s ( username ) : p r i n t " H e l l o , %s , From My F u n c t i o n ! " % ( username ) Functions may return a value to the caller, using the keyword return. For example: 1 2 def sum_two_numbers ( a , b ) : return a + b How do you Call Functions in Python? Simply write the function’s name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example): # print a simple greeting my_function ( ) 3 #p r i n t s − " H e l l o , John Doe , From My F u n c t i o n ! " 4 m y _ f u n c t i o n _ w i t h _ a r g s ( " John Doe " ) 1 2 5 6 7 # a f t e r t h i s l i n e x w i l l hold the value 3! x = sum_two_numbers ( 1 , 2 ) 8 Modules and Packages Modules in Python are itself Python files, which implement a set of functions. Modules are imported from other modules using the import command. numpy Module numpy is the fundamental package for scientific computing with Python. It contains among other things: • a powerful N-dimensional array object • sophisticated (broadcasting) functions • tools for integrating C/C++ and Fortran code • useful linear algebra, Fourier transform, and random number capabilities The main functionalities are summarized in the following example: 1 2 3 4 5 6 7 import numpy a = numpy . a r r a y ( [ [ 2 , 3 , 4 , 1 ] , [ 2 , 5 , 7 , 8 ] ] ) # a r r a y c r e a t i o n p r i n t ( " T h i s i s a %d d i m e n s i o n a l m a t r i x " % ( a . ndim ) + " with a shape of " , a . shape ) b1 = numpy . a r a n g e ( 0 , 2 4 . 1 , 0 . 1 ) b2 = numpy . l i n s p a c e ( 0 , 2 4 , 2 4 1 ) c = numpy . z e r o s ( ( 2 , 4 ) ) # c r e a t e s a r r a y f u l l o f z e r o s 8 9 10 11 12 13 14 # c d e f f B a s i c o p e r a t i o s w i t h numpy a r r a y s += 1 . 5 = a ∗ c # element wise product = numpy . d o t ( a . T , c ) # d o t p r o d u c t = numpy . sum ( a , a x i s =1) # sum o v e r s e c o n d d i m e n s i o n = numpy . s i n ( f ) # s i n u s f u n c t i o n w o r k s a l s o w i t h cos , exp , t a n . . . 15 # Printing Arrays p r i n t " M i n i m a l / maximal v a l u e o f a : %d/%d " % ( a . min ( ) , a . max ( ) ) 18 p r i n t f 16 17 19 # Deep Copy 21 a_copy = a . copy ( ) # a new a r r a y o b j e c t w i t h new d a t a i s c r e a t e d 20 22 23 24 25 26 27 28 29 30 31 # I n d e x i n g , S l i c i n g and I t e r a t i n g g = numpy . a r a n g e ( 1 0 ) ∗ ∗ 3 ∗ numpy . p i p r i n t " F i r s t e l e m e n t : %d , l a s t e l e m e n t : %d " % ( g [ 0 ] , g [ − 1 ] ) p r i n t " T h i r d e l e m e n t : %.1 f " % ( g [ 2 ] ) print " Third to f i f t h element : " , g [ 2 : 5 ] g [ : 6 : 2 ] = −1000 # e q u i v a l e n t t o g [ 0 : 6 : 2 ] = −1000; # from s t a r t t o p o s i t i o n 6 , # e x c l u s i v e , s e t e v e r y 2 nd e l e m e n t t o −1000 print "g reversed : " , g [:: −1] Useful information for MATLAB users: http://wiki.scipy.org/NumPy_for_Matlab_Users 9 matplotlib . pyplot Module matplotlib . pyplot is a python 2D plotting library and can be used in python scripts. matplotlib . pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure, e.g., create a figure, create a plotting area in a figure, plot some lines in a plotting area, decorate the plot with labels, etc. . Here is an example which shows some selected functionalities of matplotlib . pyplot 1 2 3 4 5 6 7 import m a t p l o t l i b . p y p l o t a s p l t x = [1 ,2 ,3 ,4] y = [2 ,5 ,9 ,20] p l t . p l o t ( x , y , ’ r−− ’ , l i n e w i d t h =2, l a b e l= ’ T e s t i n g ’ ) p l t . x l a b e l ( r ’ $x \ , [ \ rm{ u n i t s } ] $ ’ , f o n t s i z e =20) p l t . y l a b e l ( r ’ $y \ , [ \ rm{a_0 } ] $ ’ , f o n t s i z e =20) p l t . l e g e n d ( l o c= ’ l o w e r r i g h t ’ , p r o p={ ’ s i z e ’ : 2 0 } ) 8 9 10 # You can e i t h e r show t h e p l o t . . . p l t . show ( ) 11 # . . . or save i t to a f i l e . #f i g _ f i d = ’ t e s t . png ’ 14 #p l t . s a v e f i g ( f i g _ f i d , f o r m a t =’ png ’ , d p i =100) 15 #p l t . c l o s e ( ) 12 13 Exercises 1. Write a program which determines numerically the integral of the one-dimensional sine function y(x) = sin (x) in an interval of [0, π], using the summed Simpson’s rule. Hint: Simpson’s rule is defined by ˆ b b−a a+b y (x) dx ≈ y (a) + 4y + y (b) . 6 2 a Your task is the following: Write a function simps(x,y) computing the Simpson’s integral. Vary systematically the number of points in the x variable and plot the integral values against the number of grid points. Optimize the number of grid point until the error (difference between analytical and numerical integral) is smaller than 10−7 . 2. Repeat the procedure from task 1 using the trapezoidal rule and plot the difference between both methods on a logarithmic scale as a function of the number of grid points. References http://www.numpy.org/ http://matplotlib.org/index.html http://www.learnpython.org/en/Welcome https://docs.python.org/ 10