Python server-side scripting language

Lecture




Introduction
Python overview. Advantages and disadvantages
  • The merits of the language
  • Language flaws
    Feature Overview
  • Tuple
  • List
  • Vocabulary
    Description of the language. Control structures
    Exception Handling
    Function declaration
    Class declaration
    Operators for all types of sequences (lists, tuples, strings)
    Operators for lists (list)
    Operators for dictionaries (dictionary)
    File Objects
    Other language elements and built-in functions
    Special functions for working with lists
    Importing Modules
    Standard math module
    String module
    Conclusion
    Literature and links

  Python server-side scripting language

Guido van Rossum
Guido van rossum

Introduction

In connection with the currently observed rapid development of personal computing, there is a gradual change in the requirements for programming languages. Interpreted languages ​​are beginning to play an increasing role, as the increasing power of personal computers begins to provide sufficient speed for the execution of interpreted programs. And the only significant advantage of compiled programming languages ​​is the high-speed code they create. When the speed of the program is not critical, the most appropriate choice will be the interpreted language, as a simpler and more flexible programming tool.

In this regard, consideration of the relatively new programming language Python (Python), which was created by its author Guido van Rossum in the early 90s, is of particular interest.

The development of the Python language was started in the late 1980s by Guido van Rossum, a staff member at the Dutch CWI Institute. For the distributed OS, Amoeba required an extensible scripting language, and Guido began writing Python at his leisure, borrowing some lessons for the ABC language (Guido participated in the development of this programming-oriented language). In February 1991, Guido published the source text in the newsgroup alt.sources. From the very beginning, Python was designed as an object-oriented language .

Python overview. Advantages and disadvantages

Python is an interpreted, originally object-oriented programming language. It is extremely simple and contains a small number of keywords, however, it is very flexible and expressive. It is a higher level language than Pascal, C ++ and, naturally, C, which is achieved mainly due to the built-in high-level data structures (lists, dictionaries, tuples).

The merits of the language

The undoubted advantage is that the Python interpreter is implemented on almost all platforms and operating systems. The first such language was C, but its data types on different machines could occupy different amounts of memory and this served as some obstacle in writing a truly portable program. Python does not have this disadvantage.

The next important feature is the extensibility of the language, great importance is attached to this, and, as the author himself writes, the language was designed precisely as extensible. This means that there is the possibility of improving the language by all all interested programmers. The interpreter is written in C and the source code is available for any manipulations. If necessary, you can insert it into your program and use it as a built-in shell. Or, by writing your Python add-ons in C and compiling the program, get an “extended” interpreter with new features.

The next advantage is the presence of a large number of plug-in modules that provide various additional features. Such modules are written in C and at Python itself and can be developed by all sufficiently qualified programmers. As an example, the following modules:

  • Numerical Python - advanced mathematical capabilities, such as manipulating whole vectors and matrices;
  • Tkinter - building applications using a graphical user interface (GUI) based on the Tk-interface widely used on X-Windows;
  • OpenGL - the use of an extensive library of graphic modeling of two-and three-dimensional objects Open Graphics Library company Silicon Graphics Inc. This standard is supported, including, in such common operating systems as Microsoft Windows 95, OSR 2, 98 and Windows NT 4.0.

Language flaws

The only drawback noted by the author is the relatively low execution speed of the Python program, which is due to its interpretability. However, in our opinion, it is more than worth the dignity of the language when writing programs that are not very critical to speed of execution.

Feature Overview

1. Python, unlike many languages ​​(Pascal, C ++, Java, etc.), does not require the description of variables. They are created in the place of their initialization, i.e. at the first assignment of a variable to any value. This means that the type of the variable is determined by the type of the value assigned. In this respect, Python resembles Basic.
The type of the variable is not the same. Any assignment for it is correct and this only leads to the fact that the type of the variable becomes the type of the new assignable value.

2. In languages ​​such as Pascal, C, C ++, the organization of lists presented some difficulties. For their implementation, one had to study well the principles of working with pointers and dynamic memory. And even with a good qualification, the programmer, each time re-implementing the mechanisms for creating, working and destroying lists, could easily make subtle mistakes. In view of this, some tools have been created for working with lists. For example, in Delphi Pascal there is a class TList that implements lists; for C ++, the STL (Standard Template Library) library was developed, containing such structures as vectors, lists, sets, dictionaries, stacks, and queues. However, such tools are not available in all languages ​​and their implementations.

One of the distinguishing features of Python is the presence of such structures embedded in the language as tuples , lists ( lists ) and dictionaries (dictionary), which are sometimes called maps . Consider them in more detail.

    1. Tuple

      It is a bit like an array: it consists of elements and has a strictly defined length. Elements can be any value - simple constants or objects. Unlike an array, the elements of a tuple are not necessarily homogeneous. And what distinguishes a tuple from a list (list) is that a tuple cannot be changed, i.e. we cannot assign something new to the i-tuple element and cannot add new elements. Thus, a tuple can be called a constant list. Syntactically, a tuple is defined by listing all the elements, separated by a comma, and all this is enclosed in parentheses:


(1, 2, 5, 8)

    (3.14, 'string', -4)

          All items are indexed from scratch. To obtain the i-th element, you must specify the name of the Tuple then the index i in square brackets. Example:

      t = (0, 1, 2, 3, 4)

        print t [0], t [-1], t [-3]

          Result
              :
          0 4 2

                Thus, a tuple could be called a constant vector, if its elements were always homogeneous.
              1. List

                A good, private example of the list is the string (string) of the Turbo Pascal language. The elements of the line are single characters, its length is not fixed, it is possible to delete elements or, on the contrary, insert them anywhere in the line. Elements of the list can be arbitrary objects not necessarily of the same type. To create a list, it is enough to list its elements separated by commas, putting all this in square brackets:


            [3, 5.14, 's']

              ['string', (0,1,8), [1,1]]

                    Unlike tupla, lists can be modified at will. Access to the elements is the same as in the tuples. Example:

                l = [1, 's', (2,8), [0,3,4]]

                  print l [0], l [1], l [-2], l [-1] [0]

                    Result
                        :
                    1 s (2.8) 0
                      1. Vocabulary

                        It resembles the type of record (record) in Pascal or the structure (structure) in C. However, instead of the scheme "record field" - "value", the "key" - "value" is used here. The dictionary is a set of pairs "key" - "value". Here the “key” is a constant of any type (but mostly strings are used), it serves to name (index) some corresponding value (which can be changed).


                        A dictionary is created by listing its elements (key-value pairs separated by a colon), separated by a comma and enclosing all of this in braces. To gain access to a certain value, it is necessary, after the dictionary name, to write the corresponding key in square brackets. Example:

                    d = {'a': 1, 'b': 3, 5: 3.14, 'name': 'John'}

                      d ['b'] = d [5]

                        print d ['a'], d ['b'], d [5], d ['name']

                          Result
                              :
                          1 3.14 3.14 John

                                To add a new “key” - “value” pair, just assign the corresponding value to the element with a new key:

                            d ['new'] = 'new value'

                              print d

                                Result
                                    :
                                {'a': 1, 'b': 3, 5: 3.14, 'name': 'John', 'new': 'new value'}

                                3. Python, unlike Pascal, C, C ++ does not support work with pointers, dynamic memory and address arithmetic. In this, it is similar to Java. As you know, pointers are a source of subtle errors and work with them refers more to programming at a low level. For greater reliability and simplicity, they were not included in Python.

                                4. One of the features of Python is how one variable is assigned to another, i.e. when variables are on both sides of the operator " = ".

                                Following Timothy Badd ([1]), we will call pointer semantics a case where assignment leads only to assignment of a link (pointer), i.e. the new variable becomes just another name, denoting the same chunk of memory as the old variable. In this case, a change in the value indicated by a new variable will lead to a change in the value of the old one, since they actually mean the same thing.

                                When assignment leads to the creation of a new object (here the object is in the sense of a section of memory for storing a value of some type) and copying into it the contents of the assigned variable, this case is called the copying semantics . Thus, if the copying semantics is in effect when copying, then variables on both sides of the "=" sign will mean two independent objects with the same content. And here the subsequent change of one variable will not affect the other.

                                Assignment in Python takes place as follows: if the object being assigned is an instance of such types as numbers or strings, the copying semantics are in effect, but if there is an instance of a class, a list, a dictionary or a tuple on the right side, then the semantics of pointers is valid. Example:
                                a = 2; b = a; b = 3
                                print 'copying semantics: a =', a, 'b =', b
                                a = [2,5]; b = a; b [0] = 3
                                print 'pointer semantics: a =', a, 'b =', b
                                Result :
                                copy semantics: a = 2 b = 3
                                pointer semantics: a = [3,5] b = [3,5]

                                For those of you who want to know what's the matter, I'll give a different look at assignment in Python. If in languages ​​such as Basic, Pascal, C / C ++ we dealt with “capacitance” variables and the constants stored in them (numeric, character, string are not important), the assignment operation meant “entering” the constant into the assigned variable , then in Python we should already work with variable- "names" and the objects named by them. (Notice some analogy with the Prolog language?) What is an object in Python? This is all that you can give a name: numbers, strings, lists, dictionaries, instances of classes (which are called objects in Object Pascal), classes themselves (!), Functions, modules, etc. So, when a variable is assigned to an object, the variable becomes its "name", and such an "object" can have any number of such names and they all do not depend on each other.

                                Now, objects are divided into modifiable (mutable) and unchanged. Mutated - those that can change their "internal content", for example, lists, dictionaries, instances of classes. And invariable - such as numbers, tuples, strings (yes, strings too; you can assign a new string to a variable, obtained from the old one, but the old string itself cannot be modified).

                                So, if we write a = [2,5]; b = a; b [0] = 3 , Python interprets this as follows:

                                • give the object "list [2,5] " the name a ;
                                • give this object another name - b ;
                                • modify the zero element of the object.

                                Here also pseudo pointer semantics has turned out.

                                And the last thing to say about this: although there is no possibility of changing the structure of a tuple, the mutable components contained in it are still available for modification:

                                  t = (1, 2, [7,5], 'string') 
                                  t [0] = 6 # so it is impossible 
                                  del t [1] # error too 
                                  t [2] [1] = 0 # is valid, now the third component is the list [7,0] 
                                  t [3] [0] = 'S' # error: strings are not mutable 
                                 

                                5. Quite original is the way operators are grouped in Python. In Pascal, beginner-end operator brackets are used for this, in C, C ++, Java, curly brackets {}, in Basic, closing endings of language constructs are used (NEXT, WEND, END IF, END SUB).
                                In Python, everything is much simpler: selecting a block of statements is done by shifting the selected group by one or more spaces or tabs to the right relative to the header of the structure to which this block will belong. For example:

                                  if x> 0: 
                                  print 'x> 0' 
                                  x = x - 8 
                                  else: 
                                  print 'x <= 0' 
                                  x = 0 
                                Thereby, a good writing style of programs, which teachers of Pascal, C ++, Java, etc. call for, is acquired here from the very beginning, since it simply will not work out otherwise.

                                Description of the language. Control structures

                                if <condition1> : <operator1>
                                [ elif <condition2> : <operator2>] *
                                [ else : <operator3>]



                                The if operator. The part in square brackets is optional. The symbol “*” following the brackets means that the part enclosed in brackets can be written repeatedly one after the other.

                                Here, if the <condition1> is true, <operator1> will be executed and the elif and else branches will be ignored. Otherwise, if <condition2> is true, then <operator2> is executed, the else branch is ignored. Otherwise, <operator3> is executed.

                                while <condition> :
                                <operator1>
                                [ else: <operator2>]
                                The cycle "bye". <Operator1> will be executed all the time while <condition> is true. At normal completion of the cycle, i.e. without the use of break , <operator2> will be executed.
                                for <variable> in <list> :
                                <operator1>
                                [ else: <operator2>]  
                                The cycle "for". <Variable> runs through all the elements of <list> and <statement1> is executed for each current value of <variable>. With a normal cycle, i.e. without the use of break , <operator2> will be executed.
                                break Performs immediate completion of while and for loops.
                                continue Causes the next iteration of the while and for loops to be performed immediately.
                                return [<result>] Returns from a function or class method, returning a <result> value.

                                Exception Handling

                                try :
                                <operator1>
                                [ except [<exception> [ , <variable>]] :
                                <operator2>]
                                [ else <operator3>]
                                <Statement1> is executed, if an exception <exception> is raised, then <statement2> is executed. If <exception> has a value, then it is assigned to <variable>.
                                In case of successful completion of <statement1>, <statement3> is executed.
                                try :
                                <operator1>
                                finally :
                                <operator2>
                                Running <operator1>. If no exceptions occurred, then <operator2> is executed. Otherwise, <statement2> is executed and an exception is immediately raised.
                                raise <exception> [<value>]   Initiates an exception <exception> with the <value> parameter.

                                Exceptions are just strings. Example:

                                  my_ex = 'bad index'
                                 try:
                                 if bad:
                                 raise my_ex, bad
                                 except my_ex, value:
                                 print 'Error', value 

                                Function declaration

                                def <function_name> ( [
                                <parameter_list>] ):
                                <body_function>





                                Here <body_function> is a sequence of statements aligned with the text to the right of the word "def".
                                <parameter list> in its most general form looks like this:
                                [<id> [, <id>] *] [<id> = <v> [, <id> = <v>] *] [, * <id>]
                                Where <id> is the variable identifier; <v> is a value.
                                The <id> parameters followed by "=" get the default <v> values.
                                If the list ends with the string "* <id>", then the id is assigned a tuple from all remaining arguments passed to the function.

                                Class declaration

                                class <class_name> [(<ancestor1>
                                [, <ancestor2>] *)] :
                                <body_class>



                                Here <class_ body> may contain assignments to variables (these variables become attributes, that is, class fields) and function definitions (which are class methods).
                                The first argument of the method is always an instance of the class that calls this method (or, in other words, to which the method is applied). By convention, this argument is called "self". The special method __init __ () is called automatically when creating an instance of a class.

                                Example:

                                  class cMyClass:
                                 def __init __ (self, val):
                                 self.value = val
                                 #
                                 def printVal (self):
                                 print 'value =', self.value
                                 #
                                 # end cMyClass
                                 obj = cMyClass (3.14)
                                 obj.printVal ()
                                 obj.value = "string now"
                                 obj.printVal () 
                                Result:
                                value = 3.14
                                value = string now

                                Operators for all types of sequences (lists, tuples, strings)

                                len (s) returns the length of s.
                                min (s) , max (s) the smallest and largest elements of s, respectively.
                                x in s true ( 1 ) if s includes an element equal to x, otherwise false ( 0 ).
                                x not in s false if s includes x, otherwise true.
                                s + t merge s and t.
                                s * n , n * s n copies of s, merged together (for example, '*' * 5 is the string '*****').
                                s [i] The i-th element of s, where i is counted from 0.
                                s [i: j] part of the elements s, starting from i to j-1 inclusive. Either i, or j, or both parameters can be omitted (i is 0 by default, j is the length of s).

                                Operators for lists (list)

                                s [i] = x The i-th element of s is replaced by x.
                                s [i: j] = t part of the elements s from i to j-1 is replaced by t (t can also be a list).
                                del s [i: j] deletes part s (as well as s [i: j] = []).
                                s.append (x) adds the element x to the end of s.
                                s.count (x) returns the number of elements s equal to x.
                                s.index (x) returns the smallest i, such that s [i] == x.
                                s.insert (i, j) the part s, starting with the i-th element, is shifted to the right, and s [i] is assigned to x.
                                s.remove (x) the same as del s [s.index (x)] - removes the first element s, equal to x.
                                s.reverse () writes the string in reverse order
                                s.sort () sorts the list in ascending order.

                                Operators for dictionaries (dictionary)

                                len (a) number of items a.
                                a [k] item with key k.
                                a [k] = x assign the x value to the element with the key k.
                                del a [k] remove a [k] from the dictionary.
                                a.items () list of pairs of tuples (key, value).
                                a.keys () list of keys
                                a.values ​​() list of values ​​a.
                                a.has_key (k) returns 1 if a has the key k, otherwise 0.

                                Файловые объекты

                                Создаются встроенной функцией open() (ее описание смотрите ниже). Например: f = open ('mydan.dat','r') .
                                Методы:

                                f.close () закрыть файл.
                                f.read ( [size] ) читает < size > байт из файла и возвращает в виде строки. Если < size > отсутствует, то читает до конца файла.
                                f.readline () читает целиком одну строку из файла.
                                f.readlines () читает строки до конца файла и возвращает список прочитанных строк.
                                f.seek (offset, mode)


                                устанавливает позицию в файле с которого будет произведено чтение.
                                < offset > - смещение относительно:
                                a) начала файла (при mode == 0 - по умолчанию);
                                b) текущей позиции (при mode == 1 );
                                c) конца файла (при mode == 2).
                                f.tell () возвращает текущую позицию в файле.
                                f.write (str) записывает строку < str > в файл.

                                Другие элементы языка и встроенные функции

                                = присваивание.
                                print [ < c1 > [ , < c2 >]* [ , ] ] выводит значения < c1 >, < c2 > в стандартный вывод. Ставит пробел между аргументами. Если запятая в конце перечня аргументов отсутствует, то осуществляет переход на новую строку.
                                abs (x) возвращает абсолютное значение x.
                                apply ( f , <аргументы> ) вызывает функцию (или метод) f с < аргументами >.
                                chr (i) возвращает односимвольную строку с ASCII кодом i.
                                cmp (x, y) возвращает отрицательное, ноль, или положительное значение, если, соответственно, x <, ==, или > чем y.
                                divmod (a, b) возвращает тьюпл (a/b, a%b), где a/b - это a div b (целая часть результата деления), a%b - это a mod b (остаток от деления).
                                eval (s)
                                возвращает объект, заданный в s как строка (string). S может содержать любую структуру языка. S также может быть кодовым объектом, например: x = 1 ; incr_x = eval ("x+1") .
                                float (x) возвращает вещественное значение равное числу x.
                                hex (x) возвращает строку, содержащую шестнадцатеричное представление числа x.
                                input ( <строка> ) выводит <строку>, считывает и возвращает значение со стандартного ввода.
                                int (x) возвращает целое значение числа x.
                                len (s) возвращает длину (количество элементов) объекта.
                                long (x) возвращает значение типа длинного целого числа x.
                                max (s) , min (s) возвращают наибольший и наименьший из элементов последовательности s (т.е. s - строка, список или тьюпл).
                                oct (x) возвращает строку, содержащую представление числа x.
                                open ( <имя файла> , <режим>='r' ) возвращает файловый объект, открытый для чтения. <режим> = 'w' - открытие для записи.
                                ord (c) возвращает ASCII код символа (строки длины 1) c.
                                pow (x, y) возвращает значение x в степени y.
                                range ( <начало> , <конец> , <шаг> ) возвращает список целых чисел, больших либо равных <начало> и меньших чем <конец>, сгенерированных с заданным <шагом>.
                                raw_input ( [ <текст> ] ) prints <text> to standard output and reads a string from the standard input.
                                round (x, n = 0) returns the real x, rounded to the nth decimal place.
                                str ( <object> ) returns a string representation of <object>.
                                type ( <object> ) returns the type of the object.
                                For example: if type (x) == type (''): print 'is a string'
                                xrange ( <start> , <end> , <step> ) similar to range, but only simulates a list without creating it. Used in a for loop.

                                Special functions for working with lists

                                filter ( <function> , <list> ) возвращает список из тех элементов <спиcка>, для которых <функция> принимает значение "истина".
                                map ( <функция> , <список> ) применяет <функцию> к каждому элементу <списка> и возвращает список результатов.
                                reduce ( f , <список> ,
                                [ , <начальное значение> ] )







                                возвращает значение полученное "редуцированием" <списка> функцией f. Это значит, что имеется некая внутренняя переменная p, которая инициализируется <начальным значением>, затем, для каждого элемента <списка>, вызывается функция f с двумя параметрами: p и элементом <списка>. Возвращаемый f результат присваивается p. После перебора всего <списка> reduce возвращает p.
                                С помощью данной функции можно, к примеру, вычислить сумму элементов списка:
                                 def func (red, el):
                                   return red+el
                                sum = reduce (func, [1,2,3,4,5], 0)
                                # теперь sum == 15
                                 
                                lambda [<список параметров>] : <выражение>





                                "анонимная" функция, не имеющая своего имени и записываемая в месте своего вызова. Принимает параметры, заданные в <списке параметров>, и возвращает значение <выражения>. Используется для filter, reduce, map. For example:
                                 >>>print filter (lambda x: x>3, [1,2,3,4,5])
                                [4, 5]
                                >>>print map (lambda x: x*2, [1,2,3,4])
                                [2, 4, 6, 8]
                                >>>p=reduce (lambda r, x: r*x, [1,2,3,4], 1)
                                >>>print p
                                  24 
                                 

                                Импортирование модулей

                                import <модуль1> [ , <модуль2> ]* подключает внешние модули.
                                from <модуль> import <имя1> [ , <имя2> ]* импортирует имена (функций, классов, переменных и т.д.) из <модуля>.
                                from <модуль> import * импортирует все имена из <модуля>, за исключением начинающихся символом "_".

                                Стандартный модуль math

                                Переменные: pi , e .
                                Функции (аналогичны функциям языка C):

                                acos(x) cosh(x) ldexp(x,y) sqrt(x)
                                asin(x) exp(x) log(x) tan(x)
                                atan(x) fabs(x) sinh(x) frexp(x)
                                atan2(x,y) floor(x) pow(x,y) modf(x)
                                ceil(x) fmod(x,y) sin(x)
                                cos(x) log10(x) tanh(x)

                                Модуль string

                                Functions:

                                index (s, sub, i=0) возвращает индекс первого вхождения подстроки sub в строку s, начиная с позиции i.
                                lower (s) возвращает строку s в нижнем регистре букв.
                                splitfields (s, sep) возвращает список подстрок строк s разделенных символом sep.
                                joinfields ( <слова> , <разделитель> ) сцепляет список или тьюпл <слова> используя <разделитель>.
                                strip (s) возвращает строку, полученную из s путем исключения пробелов.
                                upper (s) возвращает строку s в верхнем регистре букв.

                                Conclusion

                                Благодаря простоте и гибкости языка Python, его можно рекомендовать пользователям (математикам, физикам, экономистам и т.д.) не являющимся программистами, но использующими вычислительную технику и программирование в своей работе.
                                Программы на Python разрабатываются в среднем в полтора-два (а порой и в два-три) раза быстрее нежели на компилируемых языках (С, С++, Pascal). Поэтому, язык может представлять не малый интерес и для профессиональных программистов, разрабатывающих приложения, не критичные к скорости выполнения, а также программы, использующие сложные структуры данных. В частности, Python хорошо зарекомендовал себя при разработке программ работы с графами, генерации деревьев.

                                Литература и ссылки

                                1. Budd T. Object-Oriented Programming. - SPb .: Peter, 1997.
                                2. Guido van Rossum . Python tutorial. (www.python.org)
                                3. Chris Hoffman . A Python Quick Reference. (www.python.org)
                                4. Guido van Rossum . Python Library Reference. (www.python.org)
                                5. Guido van Rossum . Python Reference Manual. (www.python.org)
                                6. Guido van Rossum . Seminar on programming in Python. (http://sultan.da.ru)

                                Comments


                                To leave a comment
                                If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
                                To reply

                                Programming Languages and Methods / Translation Theory

                                Terms: Programming Languages and Methods / Translation Theory