Python for Odoo Development

Introduction Python is a general purpose interpreted, interactive, object-oriented and high-level programming language. Python was crea...



Introduction

Python is a general purpose interpreted, interactive, object-oriented and high-level programming language. Python was created by Guido van Rossum in the late eighties and early nineties. Like Perl, Python source code is also now available under the GNU General Public License (GPL).
 
 
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
 
 
The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site, http://www.python.org/, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.
 
 
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, Small Talk, and Unix shell and other scripting languages.
 
 
Python is copyrighted, Like Perl, Python source code is now available under the GNU General Public License(GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing it's progress.
 
 

2. Installation

 
Nowadays most commonly used operating systems are linux or windows. I have listed installations for both the operating systems.
 
 
Linux : 
             1. Open the terminal for the linux prompt.
             2. Just type the following command to Install python
 
             $ sudo apt-get install python
 
Windows : 
            1. Go to the link to download python http://www.python.org/getit/
            2. Download the python for windows.
            3. Double click the installer (.exe) file to install the python.
            4. Go through the installation wizard and complete the process.
 
 

3. Features 

 
 
There are many features of python which are listed below. All the features make python a very useful fast and efficient language to develop applications.
 
−  Simple
−  Easy to use
−  Free and open source
−  Portable
−  Interpreted
−  Scalable
−  Extensive Libraries
 
Python is a very simple language, the constructs the syntaxes are very simple and are almost similar to other programming languages.
 
It is very easy to use python language. Compared to other programing language python provides some of the syntactical advantages which makes python very easy.
 
Python is freely available for the users with variety of versions. The biggest advantage of python is that it is Open Source.
 
Just like other open source languages python is portable and can run on various different platforms.
 
Python is an interpreted language. We don't need to compile the python files before running it because it interprets the files on runtime. 
 
Python supports scalability that means it supports large programs containing many processes. 
 
Python also supports extensive libraries where you can integrate with other languages and APIs available for some Hardware Systems. 
 

4. Working with Python

− Working with Python Interpreter
− Running python file from the terminal
− Working with Eclipse and Sublime IDE
 

5. Basics

Explicit line joining using '\' operator
 
The Explicit Line joining is used to break the code in multiple lines if it's a long code and becomes cumbersome to write in a single line. Using the '\' operator you can break the code in multiple lines. The interpreter will consider this as a single line only.
 
Example: 
              print ":EXPLICIT LINE JOINING EXAMPLE"
              x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
              print "ALL ITEMS", x
              print "NUMBES DIVISIBLE BY 2 and 3" 
              for item in x:
                    if item % 2 == 0 and \
                       item % 3 == 0:
                       print "ITEM", item
Output:
             :EXPLICIT LINE JOINING EXAMPLE
              ALL ITEMS [1, 2, 3, 4, 5, 6, 7, 8, 9]
              NUMBES DIVISIBLE BY 2 and 3
              ITEM 6
 
Escape Sequences
The Escape sequences are the same as other languages which are specially used in strings. We have been using many of them very widely for e.g. \n, \t, \', \” etc. 
 
Example:
           print ":ESCAPE SEQUENCE EXAMPLE"
           print "RESPECTED SIR,\nTHIS IS TO NOTIFY THAT I HAVE COMPLETE
           THE FOLLOWING PHASES\n\tANALYSIS\n\tDESIGN\n\nKINDLY GO
           THROUGH IT AND DO THE \"NEEDFUL\"." 
 Output:
         :ESCAPE SEQUENCE EXAMPLE
         RESPECTED SIR,
         THIS IS TO NOTIFY THAT I HAVE COMPLETE THE FOLLOWING PHASES
         ANALYSIS
         DESIGN
 
         KINDLY GO THROUGH IT AND DO THE "NEEDFUL".

Identation:
 
Identation is very important with python. As we discussed earlier in it's feature we said python is simple and easy to use. Here you don't need to keep any brackets to denote that where your block starts and where it ends. If you want to right something under a control structure or a function you just need to keep the next line idented by a space. Conventions suggest to keep four spaces/tab to keep identation so that your code looks decorated. Identation is compulsory in case of control structures, functions or classes. If you don't keep identation it would raise an error.

Example:
               print ":IDENTATION EXAMPLE"
               for i in range(1, 10):
                     if i % 2 == 0:
                        print "EVEN No", i

Output: 
             :IDENTATION EXAMPLE
              EVEN No 2
              EVEN No 4
              EVEN No 6
              EVEN No 8


Undefined Variables: 

In python we have a feature that we don't need to declare variables prior to their use. There is no boundary for variables and we don't need to remember their data types as we can assign the variable to any kind of data type. We can assign a number to variable x again we can assign a string to it without any process.

Example: 
              x = 10
                 print ":XXX", x, "TYPE::", type(x)
                 x = [1
, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                 print ":XXX", x, "TYPE::", type(x)
                 x = 'Odoo Consulting Services'
                 print ":XXX", x, "TYPE::", type(x) 

 Output:
              :XXX 10 TYPE::
              :XXX [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] TYPE::
              :XXX Odoo Consulting Services TYPE::




 SIngle Line Coding:


Python provides a facility called single line coding which means if there is a two line code having identation you can write those two lines in a single line. Thus you can save lines of code and your code looks optimized.

Example: 
                x = 10
                if x > 5: print "X is greater than 5", x


dir() Method:

This method is used for all the variables or literals. This is a method of all the data types. This method lists outs all the functions and attributes of a variable which can be used with it.

Example: 
                a = 10
                print dir(a)

Output:
 ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__',
'__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__',
'__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__',
'__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__',
'__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__',
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__',
'__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__',
'__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 
'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']


6. Basic Datatypes

Strings:
 
In Python a single character or a group of characters are strings. The string can be represented using a single quote or a double qoute. Below are the examples of strings. '' will be considered as False in strings.

Example:
               stex = 'Python'
               print stex, type(stex)
               stx = 's'
               print stx, type(stex)
               strx_null = '' #This is False with String
               print strx_null, type(strx_null)


 Output: 
              Python
              s
              


Apart from single quotes and double quotes we have triple single quotes and triple double quotes for strings. These are basically used for documentation. Below are the examples for triple
quoted strings.


Example: 
               mult_str = '''
               This is a multiline string
               Which can be accessed as a single string variable.
               For example Odoo Consulting Services delivers trainings on a globe.
               '''

               print mult_str, type(mult_str)


               mult_str2 = """
               This is also a multiline string.
               Which will also be considered as a single line string.
               Does Cresco Solution also provides trainings?
               Yes it does.
               """

              print mult_Str2, type(mult_str2)

Output: 
             This is a multiline string
             Which can be accessed as a single string variable.
             For example Odoo Consulting Services delivers trainings on a globe.
            


             This is also a multiline string.
             Which will also be considered as a single line string.
             Yes it does.
           


Integers: 

This is another data type which is used to store integer numbers. 0 will be considered as False in integer.

Example:
                inte = 10
                print inte, type(inte)
                inte = 0 # This is False in Integer
                if inte:
                    print "INT"
                else:
                    print "NOT INT"

Output:
             10
             NOT INT


Floats: 

The Floats datatype stores the numbers with fractional values. Here the False will be 0.0.

Example: 
               flo = 4.5
               print flo, type(flo)
               flo = 0.0 # This is False in Float
               if flo:
                  print "FLOAT"
               else:
                  print "NOT FLOAT"

 Output:
              4.5
              NOT FLOAT 


Boolean: 

Boolean is a data type  which stores the logical values True or False. They are many times used as flags in the control of the program. 

Example:
               bool1 = True
               print bool1, type(bool1)
               bool2 = False # This is False in boolean and at all places!

Output: 
             True

Type Conversions:

Sometimes we need to change the type of the variables or their values based on our need. For example if we are reading some value from file it would be a string. If the value is integer we can not directly use the value in the processing before converting it into an integer.

Example: 
               c = 10
               print c,type(c)
               d = str(c)
               print d, type(d)
               e = float(c)
               print e, type(e)
               f = int(d)
               print f, type(f)

Output:
            10 <type 'int'>
            10
            10.0
            10


7. Operators

 

The operators are used to perform operations on variables. There are many type of variables
available in python as listed below.
 
     - Arithmatic Operators (+, -, *, /, **, //, %)
     - Bitwise Operators (<<, >>, &, |, ~, ^)
     - Relational Operators (<, >, <=, >=, ==, !=, <>)
     - Logical Operators (and, or, not)
 
Arithmatic Operators:
 
This operators are used to perform arithmatic operations. +, -, *, /, **, //, % are the
arithmatic operators. The use of these operators is explained below.
 
     1. + is used for addition.
     2. - is used for subtraction.
     3. * is used for multiplication.
     4. / is used for division.
     5. % is used for modulo or to get the remainder of the division.
     6. ** is used for the exponent of a number.
     7. // is used for floor division.
 
Example:
 
     a = 3
     b = 6
     c = 5
     add = a + b
     print "ADDD:", add
     sub = b - a
     print "SUB", sub
     mul = a * b
     print "MUL", mul
     div = b / a
     print "DIV", div
     mod = c % a
     print "MOD", mod
     pow = c ** a
     print "POW", pow
     floor_div = c // a
     print "FLOOR_DIV", floor_div
 
Output:
     ADDD: 9
     SUB 3
     MUL 18
     DIV 2
     MOD 2
     POW 125
     FLOOR_DIV 1
 
Bitwise Operators:
 
This operators are used to perform bitwise operations on the bits of a variable. <<, >>, &, |,
~, ^ are bitwise operators.The use of these operators is explained below.
     1. << is used for left shift operation.
     2. >> is used for right shift operation.
     3. & is used for AND operation.
     4. | is used for OR operation.
     5. ^ is used for EXOR operation.
     6. ~ is used for Compliment operation.
 
Example:
 
     a = 2
     b = 5
     left_shift = b << a # 00000101 ==> 00010100
     print "LEFT SHIFT", left_shift
     right_shift = b >> a # 00000101 ==> 00000001
     print "RIGHT SHIFT", right_shift
     bit_and = a & b # 00000010 & 00000101 ==> 00000000
     print "BIT AND", bit_and
     bit_or = a | b # 00000010 | 00000101 ==> 00000111
     print "BIT OR", bit_or
     bit_xor = a ^ b # 00000010 ^ 00000101 ==> 00000111 because XOR = ab'+ba'
     print "BIT XOR", bit_xor
     bit_not = ~a # 00000010 ==> 00000011 because negate = -(x+1)
     print "BIT NOT", bit_not
 
Output:
     LEFT SHIFT 20
     RIGHT SHIFT 1
     BIT AND 0
     BIT OR 7
     BIT XOR 7
     BIT NOT -3
 
Relational Operators:
 
Relational operators are basically used to compare variables in control statements of python
or looping statements. They are basically used to check conditions stated by the programmer. <, >,
<=, >=, ==, !=, <>, is, is not are relational operators.The use of these operators is explained below.
 
     1. < is used for less than in a condition.
     2. > is used for greater than in a condition.
     3. <= is used for less than or equal to in a condition.
     4. >= is used for greater than or equal to in a condition.
     5. == is used for equal to in a condition.
     6. != is used for not equal to in a condition.
     7. <> is also used for not equal to in a condition.
     8. 'is' is used for comparing the value to be equal.
     9. 'is not' is used for comparing the value not to be equal.
 
Example:
 
     x = 10
     if x > 5:
         print ":X IS GREATER THAN 5"
     if x < 11:
         print "X IS LESS THAN 11"
     if x >= 10:
         print "X IS GREATER THAN EQUAL TO 10"
     if x <= 10:
         print "X IS LESS THAN EQUAL TO 10"
     if x == 10:
         print "X IS EQUAL TO 10"
     if x != 5:
         print "X IS NOT EQUAL TO 5"
     if x <> 5:
         print "X IS NOT EQUAL TO 5 at all"
     if x is 10:
         print "YES, X is 10"
     if x is not 11:
         print "NO X is not 11"
 
Output:

     :X IS GREATER THAN 5
     X IS LESS THAN 11
     X IS GREATER THAN EQUAL TO 10
     X IS LESS THAN EQUAL TO 10
     X IS EQUAL TO 10
     X IS NOT EQUAL TO 5
     X IS NOT EQUAL TO 5 at all
     YES, X is 10
     NO X is not 11

Logical Operators:

The logical operators are used to perform logical operations on the expressions and are even
used in control statements and looping conditions. and, or, not are the logical operators. The use of
these operators is explained below.
     1. and is used for AND operation.
     2. or is used for OR operation.
     3. not is used for Complementing the result.
 
Example:
     x = 10
     y = 15
     if x == 10 and y == 15:
         print "BOTH CONDITION ARE TRUE"
     if x >= 10 or y != 15:
         print "ATLEASE ONE IS TRUE"
     if not x > 10:
         print "THE OPP COND IS FALSE"

Output:
     BOTH CONDITION ARE TRUE
     ATLEASE ONE IS TRUE
     THE OPP COND IS FALSE
 

8. Expressions

 
The expressions are formed by use of operators and variables. The expressions are used to

perform the operations logic which is written by the programmer. The expressions can have either
variables or literals as operands along with operators. If an operator is a unary operator it will have
a single operand but it it's a binary one it will have two operands. not, ~ etc. are unary operators.
Others are binary ones. The operator precedence remains the same like all other programming
languages.

Variable Expressions:

The variable expressions contain the variables as operand and the operators. These
expressions wil not have any literal values.

Example:
      a = 10
      b = 15
      c = 13
      d = 14
      e = 8

      result1 = a + b * c - d / e
      print "RESULT1", result1

      result2 = (a + b) * c - d / e
      print "RESULT2", result2
Output:
     RESULT1 204
     RESULT2 324

Literal Expressions:

The literal expressions contain literals instead of variables as operand and the operators.
These expressions will not have any variables.

Example:
     x = 10 * 20 + 34 - 12 / 2
     print "LITERAL EXPRESSION", x
Output:
     LITERAL EXPRESSION 228

NOTE: It is an advantage of python that you can use the python interpreter as a Calculator directly
using the literal expressions.

Heterogeneous Expressions:

The heterogeneous expressions will have both literals and variables as operands along with
the operators.

Example:
     a = 10
     b = 20

      x = a * b + 38 - 18 / 2
     print "HETEROGENEOUS EXPRESSION", x
Output:
     HETEROGENEOUS EXPRESSION 229

9.Control Flow

Control flow statements are used for controling the flow of your program according to the
conditional junctions of your algorithem. Apart from conditions you can also make iterations,
breaking some code. Skipping some code etc.Following are the control flow statements which are available in python.
      1. if – elif – else
     2. for – else
     3. while – else
     4. break
     5. continue

 if – elif – else :

This control statement is basically used to check conditions and perform block of statements
based on the condition satisfying the rule. You can use either only if, if-else, if-elif or if-elif-else asper your need. It is not compulsory to use all of them.

Example:

      x = '0.0'
     if x == '0.0':
          print 'X is Zero'
     if x == 0.0:
          print 'X is float'
      else:
          print 'X is not a float'
     if isinstance(x, int):
          print "X IS INTEGER"
     elif isinstance(x, float):
          print "X IS FLOAT"
     elif isinstance(x, bool):
          print "X IS BOOLEAN"
     elif isinstance(x, str):
          print "X IS STRING"
     else:
          print "X IS A COMPLEX DATA TYPE"

Output:
     X is Zero
     X is not a float
     X IS STRING

 

 

 

 

 

 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

0 comments