# django_session

session_key: cea54d06f86f5b0e7613bc89bcff771e
expire_date: 2010-01-28 05:03:22.766881
session_data:
  gAJ9cQEoVQN1cmxxAlgAAAAAVRJfYXV0aF91c2VyX2JhY2tlbmRxA1UpZGphbmdvLmNvbnRyaWIu
  YXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBFUEbmFtZXEFWAYAAABzZHhzYWNxBlUNX2F1dGhf
  dXNlcl9pZHEHSwF1LjI3NGI3MDVjZjQ2Y2YyZGMyYzc2M2M5YTg2YWIxYWUy


session_key: a2bfac9281490a2b6ef91390387fd262
expire_date: 2010-01-30 01:47:44.412069
session_data:
  gAJ9cQEoVQN1cmxxAlgAAAAAVRJfYXV0aF91c2VyX2JhY2tlbmRxA1UpZGphbmdvLmNvbnRyaWIu
  YXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBFUEbmFtZXEFWAQAAABBbWl0cQZVDV9hdXRoX3Vz
  ZXJfaWRxB0sBdS4yZWE2ZWFhNTU5YTAwYWI5ZDFiYzMzYWM0NTM5NzdjYQ==


# django_flatpage

url: localhost/review/html/ch05-versionControl.html
title: Chapter 1.
content:
  Table of Contents

  Module 4: Version Control
  1. Suggested Reading:





  Module 4: Version Control



  Table of Contents
  1. Suggested Reading:
  Module Objectives
    After successfully completing this module a participant will be able to:
  - Understand use of Version Control tools                            U
  - Create and use repository for daily use of assignments/projects    Ap
  - Browse exsiting repo, make changes and commit back                 Ap
  - Work collaboratively with a team on live project                   Ap




  1. Suggested Reading:
  "
        http://mercurial.selenic.com/wiki/Tutorial"
      

  Initial Session Plan

  +---------+---------------------------------+---------+ | Session | Topic  			    | Duration| +=========+=================================+=========+ | 1	  | Introduction to Course          | 5 mts   | +---------+---------------------------------+---------+ | 2	  | Why Revision Control?           | 5 mts   | |	  |	- Use case: for team	    |	      | |	  |	- Use case: for single dev  |	      | +---------+---------------------------------+---------+ | 3	  | Learning the Lingo              | 5 mts   | +---------+---------------------------------+---------+ | 4       | Let there be Repository...	    | 15 mts  | |	  | 	- Creating Repositpry.	    |	      | |	  | 	- Cloning existing Repo.    |	      | |	  |	- Branches concept 	    |         | +---------+---------------------------------+---------+ | 5	  | Navigating through history logs | 5 mts   | +---------+---------------------------------+---------+ | 6	  | Making changes in local branch  | 15 mts  | |	  |	- add	    		    |	      | |	  |	- cp			    |	      | |	  |	- rename		    |	      | |	  |	- rm			    |	      | +---------+---------------------------------+---------+ | 7	  | Sharing the changes		    | 10 mts  | |	  | 	- status		    |	      | |	  |	- pull			    |	      | |	  |	- update		    |	      | +---------+---------------------------------+---------+ | 8	  | Merging the changes		    | 20 mts  | |	  | 	- commit		    |	      | |	  |	- glog			    |	      | |	  |	- push			    |	      | |	  |	- merge			    |	      | +---------+---------------------------------+---------+ | 9	  | Handling conflicts during merge | 20 mts  | +---------+---------------------------------+---------+ | 10	  | Exporting the changes: getting  |	      | |	  | patch, diff   	   	    | 10 mts  | +---------+---------------------------------+---------+

  total session time = 110 mts


  buffer time = 10 mts


  For this course, working LAN is needed if Internet is not available.


url: localhost/review/html/ch03-ult_module_plan.html
title: Chapter 1.
content:
  Table of Contents




  Module 1: Using Linux Tools ============================
  Module Objectives ----------------------
  After successfully completing this module a participant will be able to:

  Understand the design philosophy of \*nix          	   	{U}
  Use Linux as their day-to-day operating system       		{Ap}
  Use the text processing tools such as 'grep', 'tr'   		{Ap}
  Write and execute (bash) shell scripts               		{Ap}
  Use a text editor comfortably	                       		{Ap}

  Suggested Reading -----------------------

  "In the beginning..." by Neal Stephenson
  "The Unix Programming Environment" by Kerninghan and Pike


  Initial Session Plan

  +---------+---------------------------------+---------+ | Session | Topic  			    | Duration| +=========+=================================+=========+ | 1	  | Introduction to the Course      |  5 mt   | |         |                                 |         | |         | Historical background and       |  10 mts | |         | implications. Why Unix?         |         | |         |                                 |         | |         | Getting started–logging in; 
      ls,|  10 mts | |         | date, who, cd, mkdir           |         | |         |                                 |         | |         | Getting help: 
      apropos, man,    |  10 mts | |         | info                           |         | |         |                                 |         | |         | Basic file handling: 
      cp, mv,   |  10 mts | |         | rm                             |         | |         |                                 |         | |         | First session buffer            |  5 mts  | +---------+---------------------------------+---------+ | 2	  | Command line arguments          |  5 mts  | |         |                                 |         | |	  | Basic text processing: 
      head,   |  15 mts | |	  | tail, cut, paste               |	      | |         |                                 |         | |         | Shell meta characters           |  10 mts | |         |                                 |         | |         | Looking at files: 
      cat, less   |  5 mts  | |         |                                 |         | |         | Directory structure: 
      man hier, |  5 mts  | |         | ls -l                          |         | |         |                                 |         | |         | Permissions and ownership,      |  10 mts | |         | 
      chmod, chown                  |         | +---------+---------------------------------+---------+ | 3	  | Redirection and Piping          |  10 mts | |         |                                 |         | |         | More text processing:
      grep, tr |  10 mts | |         |                                 |         | |         | Elementary regex: . ? 
       ^ $ [ ] |  15 mts | |         |                                 |         | |         | One liners: show lines n to m,  |  15 mts | |         | show directories                |         | +---------+---------------------------------+---------+ | 4       | More text processing: join,    |  10 mts | |	  | sprt, uniq
       		    |	      | |         |                                 |         | |	  | Generating a word frequency list|  10 mts | |         |                                 |         | |         | Basic editing and editors : vim,|  10 mts | |         | scite                           |         | |         |                                 |         | |         | Personalising your environment: |  10 mts | |         | .bashrc, .vimrc
                     |         | |         |                                 |         | |         | Subshells and source~
               |  10 mts | +---------+---------------------------------+---------+ | 5	  | More tools: tar, zip, diff,    |  25 mts | |         | cmp, comm
                            |         | |         |                                 |         | |         | Environment variables, set*    |  10 mts | |         |                                 |         | |         | Writing simple shell scripts    |  15 mts | +---------+---------------------------------+---------+ | 6	  | Control structures and          |  20 mts | |	  | operators in bash  		    |	      | |	  |				    |	      | |	  | Writing shell scripts	    |  30 mts | +---------+---------------------------------+---------+ | 7	  | Functions in bash scripts	    |  20 mts | |	  | 	         		    |	      | |	  | Assessment Test		    |  30 mts | +---------+---------------------------------+---------+
    

  total session time = 350 mts


  buffer time = 10 mts


url: localhost/review/html/ch01-intro.html
title: Basic Python
content:
  Basic Python



   
   



    -->




  Basic Python



  Table of Contents

  1. Introduction
  2. The Python Interpreter

  2.1. The Interactive Interpreter
  2.2. 
          ipython - An enhanced interactive Python interpreter
        

  3. Editing and running a python file
  4. Basic Datatypes and operators in Python

  4.1. Numbers
  4.2. Variables
  4.3. Strings
  4.4. Boolean

  5. The 
        while loop
      
  6. The 
        if conditional
      
  7.       raw_input()

  8. 
        int() method
      


  This document is intended to be handed out at the end of the workshop. It has been designed for Engineering students who are Python beginners and have basic programming skills. The focus is on basic numerics and plotting using Python.
  The system requirements:

  Python - version 2.5.x or newer.
  IPython
  Text editor - scite, vim, emacs or whatever you are comfortable with.



  1. Introduction
  The Python programming language was created by a dutch named Guido van Rossum. The idea of Python was conceived in December 1989. The name Python has nothing to do with the reptilian, but its been named after the 70s comedy series "Monty Python's Flying Circus", since it happens to be Guido's favourite TV series.
  Current stable version of Python is 2.6.x, although Python 3.0 is also the stable version, it is not backwards compatible with the previous versions and is hence not entirely popular at the moment. This material will focus on the 2.6.x series.
  Python is licensed under the Python Software Foundation License (PSF License) which is GPL compatible Free Software license (excepting license version 1.6 and 2.0) It is a no strings attached license, which means the source code is free to modify and redistribute.
  The Python docs define Python as "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics." A more detailed summary can be found at 
        http://www.python.org/doc/essays/blurb.html. Python is a language that has been designed to help the programmer concentrate on solving the problem at hand and not worry about the programming language idiosyncrasies.
      
  Python is a highly cross platform compatible language on account of it being an interpreted language. It is highly scalable and hence has been adapted to run on the Nokia 60 series phones. Python has been designed to be readable and easy to use

  Resources available for reference


  Web: 
            http://www.python.org

  Doc: 
            http://www.python.org/doc

  Free Tutorials: 
             Official Python Tutorial: 
              http://docs.python.org/tut/tut.html
   Byte of Python: 
            http://www.byteofpython.info/ * Dive into Python: 
            http://diveintopython.org/
          


  Advantages of Python - Why Python??


  Python has been designed for readability and ease of use. Its been designed in  such a fashion that it imposes readability on the programmer. Python does away with the braces and the semicolons and instead implements code blocks based on indentation, thus enhancing readability.
  Python is a high level, interpreted, modular and object oriented language. Python performs memory management on its own, thus the programmer need not bother about allocating and deallocating memory to variables. Python provides extensibility by providing modules which can be easily imported similar to headers in C and packages in Java. Python is object oriented and hence provides all the object oriented characteristics such as inheritance, encapsulation and polymorphism.
  Python offers a highly powerful interactive programming interface in the form of the 'Interactive Interpreter' which will be discussed in more detail in the following sections.
  Python provides a rich standard library and an extensive set of modules. The  power of Python modules can be seen in this slightly exaggerated cartoon 
            http://xkcd.com/353/
          
  Python interfaces well with most other programming languages such as C, C++  and FORTRAN.

  Although, Python has one setback. Python is not fast as some of the compiled languages like C or C++. Yet, the amount of flexibility and power more than make up for this setback.



  2. The Python Interpreter


  2.1. The Interactive Interpreter
  Typing 
          python at the shell prompt on any standard Unix/Gnu-Linux system and hitting the enter key fires up the Python 'Interactive Interpreter'. The Python interpreter is one of the most integral features of Python. The prompt obtained when the interactive interpreter is similar to what is shown below. The exact appearance might differ based on the version of Python being used. The 
          &gt;&gt;&gt; thing shown is the python prompt. When something is typed at the prompt and the enter key is hit, the python interpreter interprets the command entered and performs the appropriate action. All the examples presented in this document are to be tried hands on, on the interactive interpreter.
        
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  [GCC 4.3.2] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; 


  Lets try with an example, type 
          print 'Hello, World!' at the prompt and hit the enter key.
        
  &gt;&gt;&gt; print 'Hello, World!'
  Hello, World!


  This example was quite straight forward, and thus we have written our first line of Python code. Now let us try typing something arbitrary at the prompt. For example:
  &gt;&gt;&gt; arbit word
    File "&lt;stdin&gt;", line 1
      arbit word
              ^
  SyntaxError: invalid syntax
  &gt;&gt;&gt;


  The interpreter gave an error message saying that 'arbit word' was invalid syntax which is valid. The interpreter is an amazing tool when learning to program in Python. The interpreter provides a help function that provides the necessary documentation regarding all Python syntax, constructs, modules and objects. Typing 
          help() at the prompt gives the following output:
        
  &gt;&gt;&gt; help()

  Welcome to Python 2.5!  This is the online help utility.

  If this is your first time using Python, you should definitely check out
  the tutorial on the Internet at http://www.python.org/doc/tut/.

  Enter the name of any module, keyword, or topic to get help on writing
  Python programs and using Python modules.  To quit this help utility and
  return to the interpreter, just type "quit".

  To get a list of available modules, keywords, or topics, type "modules",
  "keywords", or "topics".  Each module also comes with a one-line summary
  of what it does; to list the modules whose summaries contain a given word
  such as "spam", type "modules spam".

  help&gt; 



  As mentioned in the output, entering the name of any module, keyword or topic will provide the documentation and help regarding the same through the online help utility. Pressing 
          Ctrl+d exits the help prompt and returns to the python prompt.
        
  Let us now try a few examples at the python interpreter.
  Eg 1:
  &gt;&gt;&gt; print 'Hello, python!'
  Hello, python!
  &gt;&gt;&gt;


  Eg 2:
  &gt;&gt;&gt; print 4321*567890
  2453852690
  &gt;&gt;&gt; 


  Eg 3:
  &gt;&gt;&gt; 4321*567890
  2453852690L
  &gt;&gt;&gt;


  Note: Notice the 'L' at the end of the output. The 'L' signifies that the
  output of the operation is of type *long*. It was absent in the previous
  example because we used the print statement. This is because *print* formats
  the output before displaying.


  Eg 4:
  &gt;&gt;&gt; big = 12345678901234567890 ** 3
  &gt;&gt;&gt; print big
  1881676372353657772490265749424677022198701224860897069000
  &gt;&gt;&gt; 


  This example is to show that unlike in C or C++ there is no limit on the
  value of an integer.


  Try this on the interactive interpreter: 
          import this


  Hint: The output gives an idea of Power of Python




  2.2. 
          ipython - An enhanced interactive Python interpreter
        
  The power and the importance of the interactive interpreter was the highlight of the previous section. This section provides insight into the enhanced interpreter with more advanced set of features called 
          ipython. Entering 
          ipython at the shell prompt fires up the interactive interpreter.
        
  $ ipython
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  Type "copyright", "credits" or "license" for more information.

  IPython 0.8.4 -- An enhanced Interactive Python.
  ?         -&gt; Introduction and overview of IPython's features.
  %quickref -&gt; Quick reference.
  help      -&gt; Python's own help system.
  object?   -&gt; Details about 'object'. ?object also works, ?? prints more.

  In [1]: 


  This is the output obtained upon firing ipython. The exact appearance may change based on the Python version installed. The following are some of the various features provided by 
          ipython:
        




  Suggestions - ipython provides suggestions of the possible methods and operations available for the given python object.


  Eg 5:
  In [4]: a = 6

  In [5]: a.
  a.__abs__           a.__divmod__        a.__index__         a.__neg__          a.__rand__          a.__rmod__          a.__rxor__
  a.__add__           a.__doc__           a.__init__          a.__new__          a.__rdiv__          a.__rmul__          a.__setattr__
  a.__and__           a.__float__         a.__int__           a.__nonzero__      a.__rdivmod__       a.__ror__           a.__str__
  a.__class__         a.__floordiv__      a.__invert__        a.__oct__          a.__reduce__        a.__rpow__          a.__sub__
  a.__cmp__           a.__getattribute__  a.__long__          a.__or__           a.__reduce_ex__     a.__rrshift__       a.__truediv__
  a.__coerce__        a.__getnewargs__    a.__lshift__        a.__pos__          a.__repr__          a.__rshift__        a.__xor__
  a.__delattr__       a.__hash__          a.__mod__           a.__pow__          a.__rfloordiv__     a.__rsub__          
  a.__div__           a.__hex__           a.__mul__           a.__radd__         a.__rlshift__       a.__rtruediv__      


  In this example, we initialized 'a' (a variable - a concept that will be discussed in the subsequent sections.) to 6. In the next line when the 
          tab key is pressed after typing '
          a.' ipython displays the set of all possible methods that are applicable on the object 'a' (an integer in this context). Ipython provides many such datatype specific features which will be presented in the further sections as and when the datatypes are introduced.
        




  3. Editing and running a python file
  The previous sections focused on the use of the interpreter to run python code. While the interpeter is an excellent tool to test simple solutions and experiment with small code snippets, its main disadvantage is that everything written in the interpreter is lost once its quit. Most of the times a program is used by people other than the author. So the programs have to be available in some form suitable for distribution, and hence they are written in files. This section will focus on editing and running python files. Start by opening a text editor ( it is recommended you choose one from the list at the top of this page ). In the editor type down python code and save the file with an extension 
        .py (python files have an extension of .py). Once done with the editing, save the file and exit the editor.
      
  Let us look at a simple example of calculating the gcd of 2 numbers using Python:

  Creating the first python script(file) :
      
  $ emacs gcd.py
    def gcd(x,y):
      if x % y == 0:
        return y
      return gcd(y, x%y)

    print gcd(72, 92)


  To run the script, open the shell prompt, navigate to the directory that contains the python file and run 
        python &lt;filename.py&gt; at the prompt ( in this case filename is gcd.py )
      

  Running the python script :
      
  $ python gcd.py
  4
  $ 


  Another method to run a python script would be to include the line

  #! /usr/bin/python

  at the beginning of the python file and then make the file executable by
  $ chmod a+x 
        filename.py

  Once this is done, the script can be run as a standalone program as follows:
  $ ./
        filename.py




  4. Basic Datatypes and operators in Python
  Python provides the following set of basic datatypes.

  Numbers: int, float, long, complex
  Strings
  Boolean



  4.1. Numbers
  Numbers were introduced in the examples presented in the interactive interpreter section. Numbers include types as mentioned earlier viz., int (integers), float (floating point numbers), long (large integers), complex (complex numbers with real and imaginary parts). Python is not a strongly typed language, which means the type of a variable need not mentioned during its initialization. Let us look at a few examples.
  Eg 6:
  &gt;&gt;&gt; a = 1 #here a is an integer variable


  Eg 7:
  &gt;&gt;&gt; lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
  &gt;&gt;&gt; lng
  122333444455555666666777777788888888999999999L #notice the trailing 'L'
  &gt;&gt;&gt; print lng
  122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
  &gt;&gt;&gt; lng+1
  122333444455555666666777777788888889000000000L



  Long numbers are the same as integers in almost all aspects. They can be used in operations just like integers and along with integers without any distinction. The only distinction comes during type checking (which is not a healthy practice). Long numbers are tucked with a trailing 'L' just to signify that they are long. Notice that in the example just lng at the prompt displays the value of the variable with the 'L' whereas 
          print lng displays without the 'L'. This is because print formats the output before printing. Also in the example, notice that adding an integer to a long does not give any errors and the result is as expected. So for all practical purposes longs can be treated as ints.
        
  Eg 8:
  &gt;&gt;&gt; fl = 3.14159 #fl is a float variable
  &gt;&gt;&gt; e = 1.234e-4 #e is also a float variable, specified in the exponential form
  &gt;&gt;&gt; a = 1
  &gt;&gt;&gt; b = 2
  &gt;&gt;&gt; a/b #integer division
  0
  &gt;&gt;&gt; a/fl #floating point division
  0.31831015504887655
  &gt;&gt;&gt; e/fl
  3.9279473133031364e-05



  Floating point numbers, simply called floats are real numbers with a decimal point. The example above shows the initialization of a float variable. Shown also in this example is the difference between integer division and floating point division. 'a' and 'b' here are integer variables and hence the division gives 0 as the quotient. When either of the operands is a float, the operation is a floating point division, and the result is also a float as illustrated.
  Eg 9:
  &gt;&gt;&gt; cplx = 3 + 4j #cplx is a complex variable
  &gt;&gt;&gt; cplx
  (3+4j)
  &gt;&gt;&gt; print cplx.real #prints the real part of the complex number
  3.0
  &gt;&gt;&gt; print cplx.imag #prints the imaginary part of the complex number
  4.0
  &gt;&gt;&gt; print cplx*fl  #multiplies the real and imag parts of the complex number with the multiplier
  (9.42477+12.56636j)
  &gt;&gt;&gt; abs(cplx) #returns the absolute value of the complex number
  5.0


  Python provides a datatype for complex numbers. Complex numbers are initialized as shown in the example above. The 
          real and 
          imag operators return the real and imaginary parts of the complex number as shown. The 
          abs() returns the absolute value of the complex number.
        



  4.2. Variables
  Variables are just names that represent a value. Variables have already been introduced in the various examples from the previous sections. Certain rules about using variables:

  Variables have to be initialized or assigned a value before being used.
  Variable names can consist of letters, digits and 
                underscores .
              
  Variable names cannot begin with digits, but can contain digits in them.

  In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' are all variables of various datatypes.
  Note: Python is not a strongly typed language and hence an integer variable can at a
  later stage be used as a float variable as well.





  4.3. Strings
  Strings are one of the essential data structures of any programming language. The 
          print "Hello, World!" program was introduced in the earlier section, and the 
          "Hello, World!" in the print statement is a string. A string is basically a set of characters. Strings can be represented in various ways shown below:
        
  s = 'this is a string'              # a string variable can be represented using single quotes
  s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
  s = "I have 'single-quotes' inside!"
  l = "A string spanning many lines\
  one more line\
  yet another"                        # a string can span more than a single line.
  t = """A triple quoted string does  # another way of representing multiline strings.
  not need to be escaped at the end and
  "can have nested quotes" etc."""


  Try the following on the interpreter: 
          s = 'this is a string with 'quotes' of similar kind'


  Exercise: How to use single quotes within single quotes in a string as shown in the above example without getting an error?



  4.3.1. String operations
  A few basic string operations are presented here.

  String concatenation String concatenation is done by simple addition of two strings.
          
  &gt;&gt;&gt; x = 'Hello'
  &gt;&gt;&gt; y = ' Python'
  &gt;&gt;&gt; print x+y
  Hello Python


   Try this yourself:

  &gt;&gt;&gt; somenum = 13
  &gt;&gt;&gt; print x+somenum


  The problem with the above example is that here a string variable and an integer variable are trying to be concantenated. To obtain the desired result from the above example the str(), repr() and the `` can be used.

  str() simply converts a value to a string in a reasonable form. 
            repr() creates a string that is a representation of the value.
          
  The difference can be seen in the example shown below:
  &gt;&gt;&gt; str(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000'
  &gt;&gt;&gt; repr(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000L'


  It can be observed that the 'L' in the long value shown was omitted by str(), whereas repr() converted that into a string too. An alternative way of using repr(value) is `
            value`.
          
  A few more examples:
  &gt;&gt;&gt; x = "Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go 
  to Pycon


  In the above example, notice that the '\n'(newline) character is formatted and the string is printed on two lines. The strings discussed until now were normal strings. Other than these there are two other types of strings namely, raw strings and unicode strings.

  Raw strings are strings which are unformatted, that is the backslashes(\) are not parsed and are left as it is in the string. Raw strings are represented with an 'r' at the start of a string. Let us look at an example
          
  &gt;&gt;&gt; x = r"Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go \nto Pycon


  Note: The '\n' is not being parsed into a new line and is left as it is.

  Try this yourself:

  &gt;&gt;&gt; x = r"Let's go to Pycon\"


   Unicode strings are strings where the characters are Unicode characters as opposed to ASCII characters. Unicode strings are represented with a 'u' at the start of the string. Let us look at an example:
          
  &gt;&gt;&gt; x = u"Let's go to Pycon!"
  &gt;&gt;&gt; print x
  Let's go to Pycon!






  4.4. Boolean
  Python also provides special Boolean datatype. A boolean variable can assume a value of either 
          True or 
          False (Note the capitalizations).
        
  Let us look at examples:
  &gt;&gt;&gt; t = True
  &gt;&gt;&gt; f = not t
  &gt;&gt;&gt; print f
  False
  &gt;&gt;&gt; f or t
  True
  &gt;&gt;&gt; f and t
  False






  5. The 
        while loop
      
  The Python 
        while loop is similar to the C/C++ while loop. The syntax is as follows:
      
  statement 0
  while condition:
    statement 1 #while block
    statement 2 #while block
  statement 3 #outside the while block.


  Let us look at an example:
  &gt;&gt;&gt; x = 1  
  &gt;&gt;&gt; while x &lt;= 5:
  ...   print x
  ...   x += 1
  ... 
  1
  2
  3
  4
  5





  6. The 
        if conditional
      
  The Python 
        if block provides the conditional execution of statements. If the condition evaluates as true the block of statements defined under the if block are executed.
      
  If the first block is not executed on account of the condition not being satisfied, the set of statements in the 
        else block are executed.
      
  The 
        elif block provides the functionality of evaluation of multiple conditions as shown in the example.
      
  The syntax is as follows:
  if condition :
      statement_1
      statement_2

  elif condition:
      statement_3
      statement_4
  else:
      statement_5
      statement_6


  Let us look at an example:
  &gt;&gt;&gt; n = raw_input("Input a number:")
  &gt;&gt;&gt; if n &lt; 0:
        print n," is negative"
        elif n &gt; 0:
        print n," is positive"
        else:
        print n, " is 0"





  7.       raw_input()

  In the previous example we saw the call to the raw_input() subroutine. The 
        raw_input() method is used to take user inputs through the console. Unlike 
        input() which assumes the data entered by the user as a standard python expression, 
        raw_input() treats all the input data as raw data and converts everything into a string. To illustrate this let us look at an example.
      
  &gt;&gt;&gt; input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  121

  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:PythonFreak
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;string&gt;", line 1, in &lt;module&gt;
  NameError: name 'PythonFreak' is not defined


  As shown above the 
        input() assumes that the data entered is a valid Python expression. In the first call it prompts for an integer input and when entered it accepts the integer as an integer, whereas in the second call, when the string is entered without the quotes, 
        input() assumes that the entered data is a valid Python expression and hence it raises and exception saying PythonFreak is not defined.
      
  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:'PythonFreak'
  'PythonFreak'
  &gt;&gt;&gt; 


  Here the name is accepted because its entered as a string (within quotes). But its unreasonable to go on using quotes each time a string is entered. Hence the alternative is to use 
        raw_input().
      
  Let us now look at how 
        raw_input() operates with an example.
      
  &gt;&gt;&gt; raw_input("Enter your name:")
  Enter your name:PythonFreak
  'PythonFreak'


  Observe that the 
        raw_input() is converting it into a string all by itself.
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  '121'


  Observe that 
        raw_input() is converting the integer 121 also to a string as '121'. Let us look at another example:
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  &gt;&gt;&gt; pal + 2
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  TypeError: cannot concatenate 'str' and 'int' objects
  &gt;&gt;&gt; pal
  '121'


  Observe here that the variable 
        pal is a string and hence integer operations cannot be performed on it. Hence the exception is raised.
      



  8. 
        int() method
      
  Generally for computing purposes, the data used is not strings or raw data but on integers, floats and similar mathematical data structures. The data obtained from 
        raw_input() is raw data in the form of strings. In order to obtain integers from strings we use the method 
        int().
      
  Let us look at an example.
  &gt;&gt;&gt; intpal = int(pal)
  &gt;&gt;&gt; intpal
  121


  In the previous example it was observed that 
        pal was a string variable. Here using the 
        int() method the string 
        pal was converted to an integer variable.
      

  Try This Yourself:

  &gt;&gt;&gt; stringvar = raw_input("Enter a name:")
  Enter a name:Guido Van Rossum
  &gt;&gt;&gt; stringvar
  'Guido Van Rossum'
  &gt;&gt;&gt; numvar = int(stringvar)









  Prev 
   
   


  Chapter 1. Introduction 
  Home
   


url: localhost/review/html/ch01-introduction.html
title: Chapter 1.
content:
  Table of Contents
  Introduction to the Course




  Introduction to the Course


  Engineering students use computers for a large number of curricular tasks – mostly computation centred. However, they do not see this as coding or programming tasks and usually are not even aware of the tools and techniques that will help them to handle these tasks better. This results in less than optimal use of their time and resources. This also causes difficulties when it comes tocollaboration and building on other people’s work. This course is intended to train such students in good software practices and tools for producing code and documentation.
  After successfully completing the program, the participants will be able to:

  understand how software tools work together and how they can be used in tandem to carry out tasks,
  use unix command line tools to carry out common (mostly text processing tasks,
  to generate professional documents,
  use version control effectively – for both code and documents,
  automate tasks by writing shell scripts and python scripts,
  realise the impact of coding style and readbility on quality,
  write mid-sized programs that carry out typical engineering / numerical computations such as those that involve (basic) manipulation of large arrays in an efficient manner,
  generate 2D and simple 3D plots,
  debug programs using a standardised approach,
  understand the importance of tests and the philosophy of Test Driven Development,
  write unit tests and improve the quality of code.


url: localhost/review/html/ch04-handout.html
title: Chapter 1.
content:
  Table of Contents

  LaTeX

  1. TeX &amp; LaTeX

  1.1. TeX
  1.2. LaTeX

  2. WYSIWG vs. WYSIWM
  3. Hello World

  3.1. Compiling &amp; Output
  3.2. A peek at the source

  4. Where do we want to go
  5. Some Basics

  5.1. Spaces
  5.2. Line &amp; Page Breaks
  5.3. Paragraphs
  5.4. Special Characters
  5.5. Commands
  5.6. Environments

  6. Some Structural Elements

  6.1. 
          \documentclass

  6.2. Parts, Chapters and Sections
  6.3. Top Matter
  6.4. Abstract
  6.5. Appendices
  6.6. Table of Contents

  7. Elementary Text Typesetting

  7.1. Emphasizing
  7.2. Quotation Marks
  7.3. Dashes and Hyphens
  7.4. Footnotes
  7.5. Flushleft, Flushright, and Center
  7.6. Itemize, Enumerate, and Description
  7.7. Quote, Quotation, and Verse
  7.8. Verbatim

  8. Tables, Figures and Captions

  8.1. The 
          \tabular environment
        
  8.2. Importing Graphics
  8.3. Floats
  8.4. Captions
  8.5. List of Figures, Tables
  8.6. Cross References

  9. Bibliography

  9.1. 
          thebibliography environment
        
  9.2. BibTeX

  10. Typesetting Math

  10.1. Math Mode
  10.2. Single Equations
  10.3. Basic Elements
  10.4. Multiple Equations
  10.5. Arrays and Matrices

  11. Miscellaneous Stuff

  11.1. Presentations
  11.2. Including Code
  11.3. Including files

  12. Recommended Reading






  LaTeX



  Table of Contents

  1. TeX &amp; LaTeX

  1.1. TeX
  1.2. LaTeX

  2. WYSIWG vs. WYSIWM
  3. Hello World

  3.1. Compiling &amp; Output
  3.2. A peek at the source

  4. Where do we want to go
  5. Some Basics

  5.1. Spaces
  5.2. Line &amp; Page Breaks
  5.3. Paragraphs
  5.4. Special Characters
  5.5. Commands
  5.6. Environments

  6. Some Structural Elements

  6.1. 
          \documentclass

  6.2. Parts, Chapters and Sections
  6.3. Top Matter
  6.4. Abstract
  6.5. Appendices
  6.6. Table of Contents

  7. Elementary Text Typesetting

  7.1. Emphasizing
  7.2. Quotation Marks
  7.3. Dashes and Hyphens
  7.4. Footnotes
  7.5. Flushleft, Flushright, and Center
  7.6. Itemize, Enumerate, and Description
  7.7. Quote, Quotation, and Verse
  7.8. Verbatim

  8. Tables, Figures and Captions

  8.1. The 
          \tabular environment
        
  8.2. Importing Graphics
  8.3. Floats
  8.4. Captions
  8.5. List of Figures, Tables
  8.6. Cross References

  9. Bibliography

  9.1. 
          thebibliography environment
        
  9.2. BibTeX

  10. Typesetting Math

  10.1. Math Mode
  10.2. Single Equations
  10.3. Basic Elements
  10.4. Multiple Equations
  10.5. Arrays and Matrices

  11. Miscellaneous Stuff

  11.1. Presentations
  11.2. Including Code
  11.3. Including files

  12. Recommended Reading

  Introduction
    LaTeX is a typesetting program used to produce excellently typeset documents. It is extensively used for producing high quality scientific and mathematical documents. It may also be used for producing other kinds of documents, ranging from simple one page articles or letters


  1. TeX &amp; LaTeX


  1.1. TeX
  TeX is a typesetting system designed by Donald Knuth, the renowned Computer Scientist and Emeritus professor at Stanford University. Typesetting is placing text onto a page with all the style formatting defined, so that content looks as intended.
  It was designed with two goals in mind-

  To allow anybody to produce high-quality books using a reasonable amount of effort.
  To provide a system that would give the exact same results on all computers, now and in the future

  TeX is well known for it's stability and portability.
  TeX is pronounced as "tech".
  The current version of TeX is 3.1415926 and is converging to π.



  1.2. LaTeX
  LaTeX was originally written by Leslie Lamport in the early 1980s. It is an extension of TeX, consisting of TeX macros and a program to parse the LaTeX files. It is easier to use than TeX itself, at the same time producing the same quality of output.
  LaTeX is pronounced either as "Lah-tech" or "Lay-tech"




  2. WYSIWG vs. WYSIWM
  WYSIWG is an acronym for "What You See Is What You Get". Word processors, are typically WYSIWG tools. LaTeX, TeX or other TeX based tools are not. They are typesetting or text formatting or document description programs. They can be called WYSIWM or "What You See Is What you Mean" systems, since you give a description of how things look, and LaTeX typesets the document for you.
  Here are a few reasons, why you should use LaTeX -

  LaTeX produces documents with excellent visual quality, especially mathematical and scientific documents.
  It does the typesetting to you. Typically, when one works with a word-processor, the user is doing the text formatting or typesetting along with typing out the content. LaTeX allows the user to concentrate on the content leaving aside the typesetting to LaTeX.
  It is light on your resources as compared to most of the word processors available today.
  It is well known for it's stability and for it's virtually bug free code base.
  It encourages users to structure documents by meaning rather than appearance, thereby helping produce well structured documents.
  It uses plain text files as input, which have a lot of well known advantages over binary files. To state a few, they can be opened with any editor on any operating system, they are smaller in size compared to the binaries, can be version controlled and can be processed using widely used text processing utilities.
  The output can be generated in more than one formats.
  It is free software (free as in freedom) and gratis too.
  It is widely used.




  3. Hello World
  OK, let's get started with our first LaTeX document. Open up your favorite editor and type in the following code.
  %hello.tex - First LaTeX document
  \documentclass{article}

  \begin{document}
    Hello, World!
  \end{document}


  Save the file as 
        hello.tex and open up a terminal to compile your 
        tex file to get the output in a 
        pdf format.
      


  3.1. Compiling &amp; Output
  $pdflatex hello.tex

  Output written on hello.pdf (1 page, 5733 bytes).
  Transcript written on hello.log.


  Open the 
          hello.pdf to see the output as shown.
        

  Note: The command 
          latex is often used to get the 
          dvi output. But, throughout this course, we shall use pdflatex to compile our documents.
        



  3.2. A peek at the source

  %hello.tex - First LaTeX document

  This line is a comment. LaTeX ignores this line and it is meant only for the human readers. LaTeX ignores anything after a 
            % symbol to the end of the line.
          

  \documentclass{article}

  This line is a command and sets the 
            documentclass of the document to 
            article. LaTeX has other classes like 
            report, 
            book, 
            letter, etc. The typesetting of the document varies depending on the 
            documentclass of the document.
          

  \begin{document}

  This line informs LaTeX that this is the beginning of the content of the document.

  Hello, World!

  This is the actual text displayed in the document.

  \end{document}

  This line tells LaTeX that the document is complete and LaTeX will simply ignore anything written after this line.




  4. Where do we want to go
  During the course of this session we will learn how to do various things in LaTeX and try to produce the sample document provided.



  5. Some Basics
  Before we get started with creating the document, let's try to understand a few things that would be useful during the course of this session.


  5.1. Spaces
  LaTeX treats multiple empty spaces (or lines) as a single space (or line). An empty line between two lines of text is considered as a change of paragraphs.



  5.2. Line &amp; Page Breaks
  LaTeX usually does the job of breaking up your content into lines and pages, and does it well. But under some circumstances, you might want to instruct LaTeX to break line or start a new page at a particular point.

  \\ or 
          \newline command is used to create a new line at the point where the command is issued. Appending 
          * to 
          \\,  instructs LaTeX to create a new line, without creating a new page at that point.
        



  5.3. Paragraphs
  As already mentioned, LaTeX considers an empty line between two lines of text as a new paragraph. 
          \par command may also be used to start a newline. It is equivalent to the blank line.
        
  By default LaTeX indents new paragraphs. If you do not wish to have the paragraph indented, you can use the 
          \nointend command at the beginning of the paragraph.
        



  5.4. Special Characters
  LaTeX associates special meaning to the  characters 
          ~ # $ % ^ &amp; _ { } \.
        
  To have these characters in the text of your document, you need to prefix a backslash to them. 
          \~ \# \% \$ \^ \&amp; \_ \{ \} \textbackslash




  5.5. Commands

  All LaTeX commands start with a backslash 
              \.
            
  Like the commands in Linux, they are case sensitive.
  They usually have a backslash followed by a consisting of letters only. Any character other than letters, like space, numbers or special characters terminate the command.
  The commands for producing special characters in the text, is an exception. They contain a backslash followed by a single special character.
  Commands may have parameters, which are supplied to them by enclosing them in curly braces 
              { }.
            
  They may also have a few optional parameters which are added after the name in square brackets 
              [ ].
            




  5.6. Environments
  Environments are very similar to the commands, except that they effect larger parts of the document. For example, we used the 
          document environment in our first LaTeX document.
        

  They begin with a 
              \begin and end with a 
              \end

  In general environments can be nested within each other.





  6. Some Structural Elements


  6.1. 
          \documentclass

  As already stated, the 
          documentclass command tells LaTeX, the type of the document that you intend to create. Each class has a few differences in how the content of the document is typeset. We presently have it set to the article class. Let us try changing it to the report class.
        
  Note that the top matter of the document appears in a different page for the report class.
  Some of the LaTeX classes that you may want to use are, article, proc, report, book, slides, letter.
  The 
          documentclass command also accepts a few optional parameters. For example:
        
  \documentclass[12pt,a4paper,oneside,draft]{report}

  12pt specifies the size of the main font in the document. The relative sizes of the various fonts is maintained, when the font size is changed. If no size is specified, 
          10pt is assumed by default.
        

  a4paper specifies the size of the paper to be used for the document.
        

  oneside specifies that the document will be printed only on one side of the paper. The 
          article and 
          report classes are 
          oneside by default and the 
          book class is 
          twoside.
        

  draft marks the hyphenation and justification problems in the document with a small square in the right hand margin of the document, so that they can be easily spotted.
        
  Note: Everything written in between the 
          \documentclass command and the 
          \begin{document} command is called the Preamble.
        



  6.2. Parts, Chapters and Sections
  Often documents are divided into various parts, chapters, sections and subsections. LaTeX provides an intuitive mechanism to include this in your documents. It has various commands like 
          part, 
          chapter, 
          section, 
          subsection, 
          subsubsection, 
          paragraph and 
          subparagraph. Note that all these commands are not available in all the document classes. The 
          chapter command is available only in books and reports. Also, the 
          letter document class does not have any of these commands.
        
  Let us now give our document some structure, using these commands.
  Note that you do not need to provide any numbers to the commands. LaTeX automatically takes care of the numbering. Also, you do not need to enclose the text of a block within 
          \begin and 
          \end commands. LaTeX starts a new block each time it finds a sectioning command. :
        
  \section[Short Title]{This is a very long title and the Short Title will appear in the Table of Contents.}





  6.2.1. Section Numbering
  As already, you don't need to explicitly do any numbering in LaTeX. Parts are numbered using roman numerals; Chapters and sections are numbered using decimal numbers. When the table of contents is inserted into a document, all the numbered headings automatically appear in it.
  By default LaTeX has numbering up 2 levels, i.e, the parts, chapters, sections and subsections are numbered. You can change this by setting the 
            secnumdepth counter using the 
            \setcounter command. The following command removes numbering of the subsections. Only parts, chapters and sections are numbered. :
          
  \setcounter{secnumdepth}{1}


  A sectioning command appended with an asterisk gives an unnumbered heading that is not included in the table of contents. :
  \section*{Introduction}






  6.3. Top Matter
  The information about the document such as it's title, the date, the author(s) information etc, is collectively known as the topmatter. Though there is no command called 
          topmatter, the term topmatter is frequently used in LaTeX documentation.
        
  Let us input the top matter for our document now. :
  \title{LaTeX - A How-to}
  \author{The FOSSEE Team}
  \date


  The  commands 
          \title and  
          \author are self explanatory. The 
          \date command automatically puts in today's date into the document. Now let us compile and look at the result.
        
  You would observe that the details do not appear in the document after recompilation. This is because, LaTeX has not been instructed what to do with the top matter information that you have given it. Use the 
          \maketitle command within the document environment to instruct LaTeX to place the top matter information into the document.
        



  6.4. Abstract
  Lets now place and abstract in the document using the 
          abstract environment of LaTeX. The abstract appears in the document after the topmatter but before the main body of the document. :
        
  \begin{abstract}
  The abstract abstract.
  \end{abstract}






  6.5. Appendices
  LaTeX allows for separate numbering for appendices. 
          \appendix command indicates that the sections following are to be included in the appendix. :
        
  \appendix
  \chapter{First Appendix}





  6.6. Table of Contents
  Parts, chapters or sections that have been auto numbered by LaTeX automatically appear in the Table of Contents (ToC). 
          \tableofcontents command places a the ToC, where the command has been issued.
        
  The counter 
          tocdepth specifies the depth up to which headings appear in the ToC. It can be set using the 
          \setcounter command as shown below. :
        
  \setcounter{tocdepth}{3}


  Unnumbered sections can be placed in the table of contents using the 
          \addcontentsline command as shown below. :
        
  \section*{Introduction}
  \addcontentsline{toc}{section}{Introduction}


  Note: To get the correct entries in your table of contents, you will need to run one extra compilation, each time. This is because, the entries of the table of contents are collected during each compilation of the document and utilized during the next compilation.




  7. Elementary Text Typesetting


  7.1. Emphasizing

  Italic font is generally used to emphasize text. The 
          \emph command may be used to achieve this effect in LaTeX. :
        
  This is the \emph{emphasized text}.


  If the 
          \emph command is nested within another emphasize command, LaTeX emphasized that text using normal fonts. :
        
  \emph{Did you wonder what happens when we try \emph{emphasizing text} within \emph{emphasized text}}?


   This is emphasized text, and this is emphasized text with normal font 
          , within emphasized text.
        



  7.2. Quotation Marks
  When typing in LaTeX, the double quotation mark 
          " character shouldn't be used. The grave accent `
          
   character produces the left quote and the apostrophe '
           character produces the right quote. To obtain double quotes they are, each, used twice. :
        
  `` Here is an example of putting `text' in quotes ''





  7.3. Dashes and Hyphens
  LaTeX has four dashes of different lengths. Three of them can be produces with different number of consecutive dashes. The short dashes are used for hyphens, slightly longer ones for number ranges and the longest ones for comments. The fourth one is a mathematical symbol, the minus sign. :
  The names of these dashes are: `-' hyphen, `--' en-dash, `---' em-dash and `$-$' minus sign.


  The names for these dashes are: ‘‐’ hyphen, ‘–’ en-dash, ‘—’ em-dash and ‘−’ minus sign.



  7.4. Footnotes
  With the command:
  \footnote{footnote text}


  a footnote is printed at the foot of the current page. Footnotes should always be put after the word or sentence they refer to. Footnotes referring to a sentence or part of it should therefore be put after the comma or period.
  Note: Look at the 
          \marginpar command to insert margin notes
        



  7.5. Flushleft, Flushright, and Center
  The environments 
          flushleft and 
          flushright generate paragraphs that are either left- or right-aligned.
        
  The 
          center environment generates centered text.
        



  7.6. Itemize, Enumerate, and Description
  LaTeX has three different environments for producing lists. Itemize, Enumerate and Description allow you to produce lists of various types in LaTeX.
  Itemize is used to produce unnumbered lists. The bullets of the list can be easily changed to use any character. Enumerate environment allows you to produce auto-numbered lists. The description environment, allows you to produce a list of definitions. These environments can be nested within each other, easily.
  \begin{itemize}
    \item Now we move onto some elementary \emph{Text Typesetting}.
    \item How do we get \emph{emphasized or italic text}?
    \item \emph{Did you wonder what happens when we try \emph{emphasizing text} within \emph{emphasized text}}?
    \item ``Beautiful is better than ugly.''
  \end{itemize}

  \begin{description}
    \item[Description] This list is a description list. 
    \item[Enumerate] Numbered lists are often useful.
      \begin{enumerate}
      \item First
      \item Second
      \item Third
      \item \ldots
      \end{enumerate}
    \item[Itemize] The list above this description list is an itemize list.
  \end{description}





  7.7. Quote, Quotation, and Verse
  LaTeX provides a 
          quote environment that can be used for quoting, highlighting important material, etc. :
        
  The Zen of Python
  \begin{quote}
    The Zen of Python, by Tim Peters

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
  \end{quote}


  LaTeX provides two other similar environments, the quotation and the verse environments.
  The quotation environment can be used for longer quotes which have several paragraphs, since it indents the first line of each paragraph.
  The verse environment may be used to quote verses or poems, since the line breaks are important in quoting them. The lines are separated using 
          \\\\ at the end of a line and an empty line after each verse.
        



  7.8. Verbatim
  The verbatim environment allows us to insert pre-formatted text in a LaTeX document. It is useful for inserting code samples within the document. The verbatim text needs to be enclosed between 
          \begin{verbatim} and 
          \end{verbatim}. :
        
  \begin{verbatim}
  from numpy import *
  a = linspace(0, 5, 50, endpoint = False)
  \end{verbatim}

  from numpy import *
  a = linspace(0, 5, 50, endpoint = False)


  To insert verbatim text in-line, the 
          \verb command can be used. :
        
  The verb command allows placing \verb|verbatim text| in-line. 


  The | is just an example of a delimiter character. You can use any character except letters, * or space.




  8. Tables, Figures and Captions


  8.1. The 
          \tabular environment
        
  The 
          tabular environment allows you to typeset tables in LaTeX. 
          \begin{tabular}[pos]{col fmt} command can be used to specify the parameters of the table and start creating the table.
        
  The 
          pos argument specifies the vertical position of the table relative to the baseline of the surrounding text. It can take on the values 
          t for top, 
          b for bottom, or 
          c for center.
        
  The 
          col fmt argument specifies the formatting of the columns of the table. You need to explicitly specify the formatting for each of the columns in the table. The 
          col fmt argument can take on the following values.
        










  l



  left justified column content

   




  r



  right justified column content

   




  c



  centered column content

   





  *{n}{col}





  produces 
                    n columns with the 
                    col type of formatting 
                    *{3}{c} is the same as {c c c}
                  

   



  ``|


  produces a vertical line.

   



  Now we look at how to input the actual entries of the tables. Each horizontal row in a table is separated by 
          \\. Each column entry of a row is separated by 
          &amp;.
        
  The 
          \hline command allows you to draw horizontal lines between two rows of the table. But it does not allow you do draw partial lines. 
          \cline{a-b} draws a horizontal line from column 
          a to column 
          b. :
        
  \begin{tabular}{|c|c|}
    \hline
    \verb+l+ &amp; left justified column content\\ 
    \hline
    \verb+r+ &amp; right justified column content\\ 
    \hline
    \verb+c+ &amp; centered column content\\ 
    \hline
    \verb+*{n}{col}+ &amp; produces \verb+n+ columns with the\\
                   &amp; \verb+col+ type of formatting\\
    \cline{2-2}
                   &amp;\verb+*{3}{c}+ is the same as \verb+{c c c}+ \\
    \hline
    \verb+|+ &amp; produces a vertical line\\ 
    \hline
  \end{tabular}





  8.2. Importing Graphics
  To include images in LaTeX, we require to use an additional package known as 
          graphicx.  To load a package, we use the 
          \usepackage directive in the preamble of the document. :
        
  \usepackage{graphicx}


  When compiling with 
          pdflatex command,  
          jpg, 
          png, 
          gif and 
          pdf images can be inserted.
        
  \includegraphics[optional arguments]{imagename}


  A few 
          optional arguments:
        



  width=x, 
                height=x



  If only the height or width is specified, the image is scaled, maintaining the aspect ratio.





  keepaspectratio



  This parameter can either be set to true or false. When set to true, the image is scaled according to both width and height, without changing the aspect ratio, so that it does not exceed both the width and the height dimensions.





  scale=x



  Scale the image by a factor of 
                      x. For example, 
                      scale=2, will double the image size.
                    




  angle=x



  This option can be used to rotate the image by 
                          x degrees, counter-clockwise.
                        





  \includegraphics[scale=0.8, angle=30]{lion_orig.png}





  8.3. Floats
  Tables and Figures need to be treated in a special manner, since they cannot be split over pages, and they are referred to as floats in LaTeX.
  When there is not enough space on a page, to fit in a table or figure, it is floated over to the next page filling up the current page with text. LaTeX has float environments called table and figure for tables and images, respectively.
  Anything enclosed within the table or figure environments will be treated as floats. :
  \begin{figure}[pos] or 
  \begin{table}[pos]


  The 
          pos parameter specifies the placement of the float. The possible values it can take are as follows.
        







  Specifier


  Permission





  h


  at approximately the same place where it occurs in the source




  t


  at the top of the page.




  b


  at the bottom of the page.




  p


  on a special page for floats only.




  !


  Override LaTeX's internal parameters for good positions




  H


  nearly equivalent to h!




  Examples:
  \begin{figure}[h]
  \centering
  \includegraphics[scale=0.8, angle=30]{lion_orig.png}
  \end{figure}






  8.4. Captions
  The 
          \caption{text} command allows you to add captions to images or tables. LaTeX automatically numbers your tables and figures and you need not include numbers in the captions that you write. The caption appears below or on top of the image (or table), depending on whether you place it after or before the 
          importgraphics (or 
          tabular) command.
        
  \begin{figure}[h] \centering \includegraphics[scale=0.8]{lion_orig.png} \caption{CTAN lion drawing by Duane Bibby; thanks to www.ctan.org} \end{figure}
  The caption command also, like the section command, has the short caption optional parameter. The short caption will appear in the list of tables or figures.



  8.5. List of Figures, Tables
  LaTeX can automatically generate a List of Tables or Figures, with the table or figure numbers, the captions and page numbers on which they appear. This can be done using the 
          \listoftables or 
          listoffigures commands.
        
  Note: Just like table of contents, these lists also require an extra compilation.



  8.6. Cross References
  LaTeX has a very efficient mechanism of inserting cross-references in documents.
  The command 
          \label{name} is used to label figures, tables or segments of text. 
          \ref{name} refers to the object marked by the 
          name by it's numbering (figure, table, section etc.) 
          \pageref{name} gives the page number of the object which has been labeled with 
          name.
        
  Note: Cross referencing also requires an extra compilation, like table of contents.




  9. Bibliography
  Bibliography or references can be added to LaTeX documents in two ways - using the 
        thebibliography environment, or using BibTeX. Let's first look at using the 
        \thebibliography environment and then move on to BibTeX.
      


  9.1. 
          thebibliography environment
        
  Writing bibliographies in LaTeX using the 
          thebibliography environment is pretty easy. You simply have to list down all the bibliography items within the bibliography environment.
        
  Each entry of the bibliography begins with the command 
          \bibitem[label]{name}. The name is used to cite the bibliography item within the document using  
          \cite{name}. The label option replaces the numbers from the auto enumeration with the labels given. :
        
  He used this lion in the illustrations for D Knuth's original TeXbook\cite{DKnuth}, for L Lamport's LaTeX book\cite{LLamport}

  \begin{thebibliography}{99}
    \bibitem{DKnuth} Donald E. Knuth (1984). \emph{The TeXbook} (Computers and Typesetting, Volume A). Reading, Massachusetts: Addison-Wesley. ISBN 0-201-13448-9.

    \bibitem{LLamport} Lamport, Leslie (1994). \emph{LaTeX: A document preparation system: User's guide and reference}.
     illustrations by Duane Bibby (2nd ed.). Reading, Mass: Addison-Wesley Professional. 
  \end{thebibliography}


  The 
          99 in the example above indicates the maximum width of the label that the references may get. We here assume that the number of Bibliography items will be less than 100. If your document has less than 10 references, you may want to replace 
          99 with 
          9.
        



  9.2. BibTeX
  The previous section explained the process of listing references at the end of a document and embedding cross references. In this section let us explore the BibTeX environment for keeping track of references.
  Using BibTeX is a very convenient method to use, when writing multiple documents in a single area or field. BibTeX allows you to create a database of all your references and use them as and when required.
  The BibTeX database is stored in a 
          .bib file. The structure of the file is quite simple and an example is shown below. :
        
  @book{Lamport94,
  author    = "Leslie Lamport",
  title     = "A Document Preparation System: User's Guide and Reference",
  publisher = "Addison-Wesley Professional",
  year      = "1994",
  edition    = "second",
  note      = "illustrations by Duane Bibby"
  }


  Each bibliography entry starts with a declaration of the type of the reference being mentioned. The reference is in the above example is of the book type. BibTeX has a wide range of reference types, for example, 
          article, book, conference, manual, proceedings, unpublished.
        
  The type of reference is followed by a left curly brace, and immediately followed by the citation key. The citation key, 
          Lamport94 in the example above is used to cite this reference using the command 
          \cite{Lamport94}.
        
  This is followed by the relevant fields and their values, listed one by one. Each entry must be followed by a comma to delimit one field from the other.
  To get your LaTeX document to use the bibliography database, you just add the following lines to your LaTeX document. :
  \bibliographystyle{plain}
  \bibliography{LaTeX}


  Bibliography styles are files that tell BibTeX how to format the information stored in the 
          .bib database file. The style file for this example is 
          plain.bst. Note that you do not need to add the 
          .bst extension to the filename.  If you wish to achieve a particular style of listing the bibliography items and citing them, you should use an appropriate style file.
        
  The 
          bibliography command specifies the file that should be used as the database for references. The file used in this example is 
          LaTeX.bib



  9.2.1. Compiling
  Adding BibTeX based references, slightly complicates the process of compiling the document to obtain the desired output. The exact workings of LaTeX and BibTeX will not be explained here. The procedure for obtaining the output (without any explanations) is as follows:

  Compile the 
                .tex file using 
                pdflatex - 
                $pdflatex LaTeX(.tex)

  Compile the 
                .bib file using 
                bibtex -  
                $bibtex LaTeX(.bib)

  Compile the 
                .tex file again.
              
  Compile the 
                .tex file for one last time!
              






  10. Typesetting Math
  It is advisable to use the AMS-LaTeX bundle to typeset mathematics in LaTeX. It is a collection of packages and classes for mathematical typesetting.
  We load 
        amsmath by issuing the 
        \usepackage{amsmath} in the preamble. Through out this section, it is assumed that the 
        amsmath package has been loaded.
      


  10.1. Math Mode
  There are a few differences between the 
          math mode and the 
          text mode:
        

  Most spaces and line breaks do not have any significance, as all spaces are either derived logically from the mathematical expressions, or have to be specified with special commands such as 
              \, 
              \quad or 
              \qquad

  Empty lines are not allowed.
  Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula, then you have to enter the text using the \text{...} command




  10.2. Single Equations
  Mathematical equations can be inserted in-line within a paragraph (
          text style), or the paragraph can be broken to typeset it separately (
          display style).
        
  A mathematical equation within a paragraph is entered between 
          $ and 
          $. Larger equations are set apart from the paragraph, by enclosing them within 
          \begin{equation} and 
          \end{equation}. If you don't wish to number a particular equation, the starred version of equation can be used. 
          \begin{equation*} and 
          \end{equation*}

  The equation can also be cross referenced using the 
          \label and 
          \eqref commands.
        



  10.3. Basic Elements
  Greek Letters can are entered as 
          \alpha, \beta, \gamma, \delta, ... for lowercase letters and 
          \Alpha, \Beta, \Gamma, ... for uppercase ones.
        
  Exponents and subscripts can be typeset using the carat 
          ^ and the underscore 
          _ respectively. Most of the math mode commands act only on the next character. If you want a command to affect several characters, they need to be enclosed in curly braces.
        
  The 
          \sqrt command is used to typeset the square root symbol. LaTeX of the root sign is determined automatically. The nth root is generated with 
          \sqrt[n].
        
  To explicitly show a multiplication a dot may be shown. 
          \cdot could be used, which typesets the dot to the center. 
          \cdots is three centered dots while 
          \ldots sets the dots on the baseline. Besides that 
          \vdots for vertical and 
          \ddots can be used for diagonal dots.
        
  A fraction can be typeset with the command 
          \frac{..}{..}

  The integral operator is generated with 
          \int, the sum operator with 
          \sum, and the product operator with 
          \prod. The upper and lower limits are specified with 
          ^ and 
          _ like subscripts and superscripts.
        
  LaTeX provides all kinds of braces as delimiters. The round and square brackets can be produces using the keys on the keyboard and appending a backslash. Other delimiters can be produced using special commands of LaTeX. Placing 
          \left in front of an opening delimiter and 
          \right in front of a closing delimiter, instructs LaTeX to automatically take care of the sizes of the delimiters.
        



  10.4. Multiple Equations
  Long formulae that run over several lines or equation systems, can be typeset using the 
          align or 
          align* environments. 
          align numbers each of the lines in the environment, and 
          align* as expected, does not number any of them.
        
  The 
          &amp; is used to align the equations vertically and the 
          \\ command is used to break the lines. Line numbering can be skipped for a particular line in the 
          align environment by placing a 
          \nonumber before the line break.
        
  \begin{align}
  \alpha^2 + \beta^2 &amp;= \gamma^2 \\
  \sum_{i=1}^ni &amp;= \frac{n(n+1)}{2}\\
  \sqrt{-1} &amp;= \pm1 \nonumber
  \end{align}






  10.5. Arrays and Matrices
  To typeset arrays, use the 
          array environment. It works similar to the 
          tabular environment. The 
          \\ command is used to break the lines. :
        
  \begin{equation*}
  \mathbf{X} = \left(
   \begin{array}{ccc}
   a_1 &amp; a_2 &amp; \ldots \\
   b_1 &amp; b_2 &amp; \ldots \\
   \vdots &amp; \vdots &amp; \ddots
   \end{array} \right)
  \end{equation*}


  The 
          array environment can also be used to typeset piecewise functions by using a “.” as an invisible 
          \right delimiter :
        
  \begin{equation*}
  f(x) = \left\{
   \begin{array}{rl}
     0 &amp; \text{if } x \le 0\\
     1 &amp; \text{if } x &gt; 0
   \end{array} \right.
   \end{equation*}


  Six different types of matrix environments are available in the 
          amsmath package for typesetting matrices.  They essentially have different delimiters: 
          matrix (none), 
          pmatrix (, 
          bmatrix [, 
          Bmatrix {, 
          vmatrix | and 
          Vmatrix ‖. In these matrix environments, the number of columns need not be specified, unlike the 
          array environment. :
        
  \begin{equation*}
    \begin{matrix}
    1 &amp; 2 \\
    3 &amp; 4
    \end{matrix} \qquad

    \begin{bmatrix}
    1 &amp; 2 &amp; 3 \\
    4 &amp; 5 &amp; 6 \\
    7 &amp; 8 &amp; 9
    \end{bmatrix}
  \end{equation*}






  11. Miscellaneous Stuff


  11.1. Presentations
  LaTeX has quite a few options to produce presentation slides. We shall look at the 
          beamer class, which is well developed and easy to use. We shall only briefly look at some of the features of beamer. For the best documentation, look at the beamer user guide.
        
  To write a 
          beamer presentation, it is recommended that you use one of the templates that beamer provides. We shall use the 
          speaker_introduction template to get started with beamer.
        
  As you can see, the document begins with the 
          documentclass being set to beamer.
        
  The 
          \setbeamertemplate command sets the template for various parameters. The 
          background canvas, 
          headline and 
          footline are being set using the command.
        

  \usetheme command sets the theme to be used in the presentation.
        
  Notice that each slide is enclosed within 
          \begin{frame} and 
          \end{frame} commands. The 
          \begin{frame} command can be passed the Title and Subtitle of the slide as parameters.
        
  To achieve more with beamer, it is highly recommended that you look at the 
          beameruserguide.
        



  11.2. Including Code
  The 
          listings package can be used to embed source code into your LaTeX document. We shall briefly explore inserting python code into our document.
        
  Obviously, you first need to tell LaTeX that you want it to use the 
          listings package, using the 
          \usepackage command. :
        
  \usepackage{listings}


  Then, we tell LaTeX that we are going to embed Python code into this document. A simple code highlighting for Python code can be achieved using this. :
  \lstset{language=Python,
          showstringspaces=false,
         }


  You might want to customize the code highlighting further using other variables like 
          basicstyle, 
          commentstyle, 
          stringstyle, 
          keywordstyle etc. For detailed information on all this, you should look at the 
          listings package documentation.
        
  You include a block of code into your document by enclosing it within the 
          lstlisting environment. :
        
  \begin{lstlisting}
  string="Hello, World! "
  for i in range(10):
      print string*i
  \end{lstlisting} 


  You can also include source code files directly into your latex document, using the 
          lstinputlisting command. :
        
  \lstinputlisting[lastline=20]{lstexample.py}


  This command includes the first 20 lines of the file 
          lstexample.py into out LaTeX document.
        



  11.3. Including files
  When working on a large document, it is convenient sometimes, to split the large file into smaller input files and club them together at the time of compiling.
  The 
          \input or 
          \include commands may be used to embed one LaTeX file into another. The 
          \input command is equivalent to a copy and paste of the document, just before the compilation. The 
          \include command is exactly similar, except for the fact that it creates a new page every time it is issued.
        

  \input{file} or 
          \include{file} commands will include the file 
          file1.tex with in the file where the command has been issued. Note that you do not need to specify the 
          .tex extension of the file.
        
  The 
          \includeonly is useful for debugging or testing the LaTeX document that you are creating, since it restricts the 
          \include command. Only the files which are given as arguments to the 
          \includeonly command will be included in the document (wherever a 
          \include command for those files, has been issued).
        


  11.3.1. A note on filenames
  Never use filenames or directories that contain spaces. Make filenames as long or short as you would like, but strictly avoid spaces. Stick to upper or lower case letters (without accents), the digits, the hyphen and the full stop or period.





  12. Recommended Reading


  LaTeX Wikibook


  The Not So Short Introduction to LaTeX2e by Tobias Oetikar et al..
          


url: localhost/review/html/ch02-basic_intro.html
title: Basic Python
content:
  Basic Python



  Table of Contents

  1. Introduction
  2. The Python Interpreter

  2.1. The Interactive Interpreter
  2.2. 
          ipython - An enhanced interactive Python interpreter
        

  3. Editing and running a python file
  4. Basic Datatypes and operators in Python

  4.1. Numbers
  4.2. Variables
  4.3. Strings
  4.4. Boolean

  5. The 
        while loop
      
  6. The 
        if conditional
      
  7.       raw_input()

  8. 
        int() method
      


  This document is intended to be handed out at the end of the workshop. It has been designed for Engineering students who are Python beginners and have basic programming skills. The focus is on basic numerics and plotting using Python.
  The system requirements:

  Python - version 2.5.x or newer.
  IPython
  Text editor - scite, vim, emacs or whatever you are comfortable with.



  1. Introduction
  The Python programming language was created by a dutch named Guido van Rossum. The idea of Python was conceived in December 1989. The name Python has nothing to do with the reptilian, but its been named after the 70s comedy series "Monty Python's Flying Circus", since it happens to be Guido's favourite TV series.
  Current stable version of Python is 2.6.x, although Python 3.0 is also the stable version, it is not backwards compatible with the previous versions and is hence not entirely popular at the moment. This material will focus on the 2.6.x series.
  Python is licensed under the Python Software Foundation License (PSF License) which is GPL compatible Free Software license (excepting license version 1.6 and 2.0) It is a no strings attached license, which means the source code is free to modify and redistribute.
  The Python docs define Python as "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics." A more detailed summary can be found at 
        http://www.python.org/doc/essays/blurb.html. Python is a language that has been designed to help the programmer concentrate on solving the problem at hand and not worry about the programming language idiosyncrasies.
      
  Python is a highly cross platform compatible language on account of it being an interpreted language. It is highly scalable and hence has been adapted to run on the Nokia 60 series phones. Python has been designed to be readable and easy to use

  Resources available for reference


  Web: 
            http://www.python.org

  Doc: 
            http://www.python.org/doc

  Free Tutorials: 
             Official Python Tutorial: 
              http://docs.python.org/tut/tut.html
   Byte of Python: 
            http://www.byteofpython.info/ * Dive into Python: 
            http://diveintopython.org/
          


  Advantages of Python - Why Python??


  Python has been designed for readability and ease of use. Its been designed in  such a fashion that it imposes readability on the programmer. Python does away with the braces and the semicolons and instead implements code blocks based on indentation, thus enhancing readability.
  Python is a high level, interpreted, modular and object oriented language. Python performs memory management on its own, thus the programmer need not bother about allocating and deallocating memory to variables. Python provides extensibility by providing modules which can be easily imported similar to headers in C and packages in Java. Python is object oriented and hence provides all the object oriented characteristics such as inheritance, encapsulation and polymorphism.
  Python offers a highly powerful interactive programming interface in the form of the 'Interactive Interpreter' which will be discussed in more detail in the following sections.
  Python provides a rich standard library and an extensive set of modules. The  power of Python modules can be seen in this slightly exaggerated cartoon 
            http://xkcd.com/353/
          
  Python interfaces well with most other programming languages such as C, C++  and FORTRAN.

  Although, Python has one setback. Python is not fast as some of the compiled languages like C or C++. Yet, the amount of flexibility and power more than make up for this setback.



  2. The Python Interpreter


  2.1. The Interactive Interpreter
  Typing 
          python at the shell prompt on any standard Unix/Gnu-Linux system and hitting the enter key fires up the Python 'Interactive Interpreter'. The Python interpreter is one of the most integral features of Python. The prompt obtained when the interactive interpreter is similar to what is shown below. The exact appearance might differ based on the version of Python being used. The 
          &gt;&gt;&gt; thing shown is the python prompt. When something is typed at the prompt and the enter key is hit, the python interpreter interprets the command entered and performs the appropriate action. All the examples presented in this document are to be tried hands on, on the interactive interpreter.
        
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  [GCC 4.3.2] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; 


  Lets try with an example, type 
          print 'Hello, World!' at the prompt and hit the enter key.
        
  &gt;&gt;&gt; print 'Hello, World!'
  Hello, World!


  This example was quite straight forward, and thus we have written our first line of Python code. Now let us try typing something arbitrary at the prompt. For example:
  &gt;&gt;&gt; arbit word
    File "&lt;stdin&gt;", line 1
      arbit word
              ^
  SyntaxError: invalid syntax
  &gt;&gt;&gt;


  The interpreter gave an error message saying that 'arbit word' was invalid syntax which is valid. The interpreter is an amazing tool when learning to program in Python. The interpreter provides a help function that provides the necessary documentation regarding all Python syntax, constructs, modules and objects. Typing 
          help() at the prompt gives the following output:
        
  &gt;&gt;&gt; help()

  Welcome to Python 2.5!  This is the online help utility.

  If this is your first time using Python, you should definitely check out
  the tutorial on the Internet at http://www.python.org/doc/tut/.

  Enter the name of any module, keyword, or topic to get help on writing
  Python programs and using Python modules.  To quit this help utility and
  return to the interpreter, just type "quit".

  To get a list of available modules, keywords, or topics, type "modules",
  "keywords", or "topics".  Each module also comes with a one-line summary
  of what it does; to list the modules whose summaries contain a given word
  such as "spam", type "modules spam".

  help&gt; 



  As mentioned in the output, entering the name of any module, keyword or topic will provide the documentation and help regarding the same through the online help utility. Pressing 
          Ctrl+d exits the help prompt and returns to the python prompt.
        
  Let us now try a few examples at the python interpreter.
  Eg 1:
  &gt;&gt;&gt; print 'Hello, python!'
  Hello, python!
  &gt;&gt;&gt;


  Eg 2:
  &gt;&gt;&gt; print 4321*567890
  2453852690
  &gt;&gt;&gt; 


  Eg 3:
  &gt;&gt;&gt; 4321*567890
  2453852690L
  &gt;&gt;&gt;


  Note: Notice the 'L' at the end of the output. The 'L' signifies that the
  output of the operation is of type *long*. It was absent in the previous
  example because we used the print statement. This is because *print* formats
  the output before displaying.


  Eg 4:
  &gt;&gt;&gt; big = 12345678901234567890 ** 3
  &gt;&gt;&gt; print big
  1881676372353657772490265749424677022198701224860897069000
  &gt;&gt;&gt; 


  This example is to show that unlike in C or C++ there is no limit on the
  value of an integer.


  Try this on the interactive interpreter: 
          import this


  Hint: The output gives an idea of Power of Python




  2.2. 
          ipython - An enhanced interactive Python interpreter
        
  The power and the importance of the interactive interpreter was the highlight of the previous section. This section provides insight into the enhanced interpreter with more advanced set of features called 
          ipython. Entering 
          ipython at the shell prompt fires up the interactive interpreter.
        
  $ ipython
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  Type "copyright", "credits" or "license" for more information.

  IPython 0.8.4 -- An enhanced Interactive Python.
  ?         -&gt; Introduction and overview of IPython's features.
  %quickref -&gt; Quick reference.
  help      -&gt; Python's own help system.
  object?   -&gt; Details about 'object'. ?object also works, ?? prints more.

  In [1]: 


  This is the output obtained upon firing ipython. The exact appearance may change based on the Python version installed. The following are some of the various features provided by 
          ipython:
        




  Suggestions - ipython provides suggestions of the possible methods and operations available for the given python object.


  Eg 5:
  In [4]: a = 6

  In [5]: a.
  a.__abs__           a.__divmod__        a.__index__         a.__neg__          a.__rand__          a.__rmod__          a.__rxor__
  a.__add__           a.__doc__           a.__init__          a.__new__          a.__rdiv__          a.__rmul__          a.__setattr__
  a.__and__           a.__float__         a.__int__           a.__nonzero__      a.__rdivmod__       a.__ror__           a.__str__
  a.__class__         a.__floordiv__      a.__invert__        a.__oct__          a.__reduce__        a.__rpow__          a.__sub__
  a.__cmp__           a.__getattribute__  a.__long__          a.__or__           a.__reduce_ex__     a.__rrshift__       a.__truediv__
  a.__coerce__        a.__getnewargs__    a.__lshift__        a.__pos__          a.__repr__          a.__rshift__        a.__xor__
  a.__delattr__       a.__hash__          a.__mod__           a.__pow__          a.__rfloordiv__     a.__rsub__          
  a.__div__           a.__hex__           a.__mul__           a.__radd__         a.__rlshift__       a.__rtruediv__      


  In this example, we initialized 'a' (a variable - a concept that will be discussed in the subsequent sections.) to 6. In the next line when the 
          tab key is pressed after typing '
          a.' ipython displays the set of all possible methods that are applicable on the object 'a' (an integer in this context). Ipython provides many such datatype specific features which will be presented in the further sections as and when the datatypes are introduced.
        




  3. Editing and running a python file
  The previous sections focused on the use of the interpreter to run python code. While the interpeter is an excellent tool to test simple solutions and experiment with small code snippets, its main disadvantage is that everything written in the interpreter is lost once its quit. Most of the times a program is used by people other than the author. So the programs have to be available in some form suitable for distribution, and hence they are written in files. This section will focus on editing and running python files. Start by opening a text editor ( it is recommended you choose one from the list at the top of this page ). In the editor type down python code and save the file with an extension 
        .py (python files have an extension of .py). Once done with the editing, save the file and exit the editor.
      
  Let us look at a simple example of calculating the gcd of 2 numbers using Python:

  Creating the first python script(file) :
      
  $ emacs gcd.py
    def gcd(x,y):
      if x % y == 0:
        return y
      return gcd(y, x%y)

    print gcd(72, 92)


  To run the script, open the shell prompt, navigate to the directory that contains the python file and run 
        python &lt;filename.py&gt; at the prompt ( in this case filename is gcd.py )
      

  Running the python script :
      
  $ python gcd.py
  4
  $ 


  Another method to run a python script would be to include the line

  #! /usr/bin/python

  at the beginning of the python file and then make the file executable by
  $ chmod a+x 
        filename.py

  Once this is done, the script can be run as a standalone program as follows:
  $ ./
        filename.py




  4. Basic Datatypes and operators in Python
  Python provides the following set of basic datatypes.

  Numbers: int, float, long, complex
  Strings
  Boolean



  4.1. Numbers
  Numbers were introduced in the examples presented in the interactive interpreter section. Numbers include types as mentioned earlier viz., int (integers), float (floating point numbers), long (large integers), complex (complex numbers with real and imaginary parts). Python is not a strongly typed language, which means the type of a variable need not mentioned during its initialization. Let us look at a few examples.
  Eg 6:
  &gt;&gt;&gt; a = 1 #here a is an integer variable


  Eg 7:
  &gt;&gt;&gt; lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
  &gt;&gt;&gt; lng
  122333444455555666666777777788888888999999999L #notice the trailing 'L'
  &gt;&gt;&gt; print lng
  122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
  &gt;&gt;&gt; lng+1
  122333444455555666666777777788888889000000000L



  Long numbers are the same as integers in almost all aspects. They can be used in operations just like integers and along with integers without any distinction. The only distinction comes during type checking (which is not a healthy practice). Long numbers are tucked with a trailing 'L' just to signify that they are long. Notice that in the example just lng at the prompt displays the value of the variable with the 'L' whereas 
          print lng displays without the 'L'. This is because print formats the output before printing. Also in the example, notice that adding an integer to a long does not give any errors and the result is as expected. So for all practical purposes longs can be treated as ints.
        
  Eg 8:
  &gt;&gt;&gt; fl = 3.14159 #fl is a float variable
  &gt;&gt;&gt; e = 1.234e-4 #e is also a float variable, specified in the exponential form
  &gt;&gt;&gt; a = 1
  &gt;&gt;&gt; b = 2
  &gt;&gt;&gt; a/b #integer division
  0
  &gt;&gt;&gt; a/fl #floating point division
  0.31831015504887655
  &gt;&gt;&gt; e/fl
  3.9279473133031364e-05



  Floating point numbers, simply called floats are real numbers with a decimal point. The example above shows the initialization of a float variable. Shown also in this example is the difference between integer division and floating point division. 'a' and 'b' here are integer variables and hence the division gives 0 as the quotient. When either of the operands is a float, the operation is a floating point division, and the result is also a float as illustrated.
  Eg 9:
  &gt;&gt;&gt; cplx = 3 + 4j #cplx is a complex variable
  &gt;&gt;&gt; cplx
  (3+4j)
  &gt;&gt;&gt; print cplx.real #prints the real part of the complex number
  3.0
  &gt;&gt;&gt; print cplx.imag #prints the imaginary part of the complex number
  4.0
  &gt;&gt;&gt; print cplx*fl  #multiplies the real and imag parts of the complex number with the multiplier
  (9.42477+12.56636j)
  &gt;&gt;&gt; abs(cplx) #returns the absolute value of the complex number
  5.0


  Python provides a datatype for complex numbers. Complex numbers are initialized as shown in the example above. The 
          real and 
          imag operators return the real and imaginary parts of the complex number as shown. The 
          abs() returns the absolute value of the complex number.
        



  4.2. Variables
  Variables are just names that represent a value. Variables have already been introduced in the various examples from the previous sections. Certain rules about using variables:

  Variables have to be initialized or assigned a value before being used.
  Variable names can consist of letters, digits and 
                underscores .
              
  Variable names cannot begin with digits, but can contain digits in them.

  In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' are all variables of various datatypes.
  Note: Python is not a strongly typed language and hence an integer variable can at a
  later stage be used as a float variable as well.





  4.3. Strings
  Strings are one of the essential data structures of any programming language. The 
          print "Hello, World!" program was introduced in the earlier section, and the 
          "Hello, World!" in the print statement is a string. A string is basically a set of characters. Strings can be represented in various ways shown below:
        
  s = 'this is a string'              # a string variable can be represented using single quotes
  s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
  s = "I have 'single-quotes' inside!"
  l = "A string spanning many lines\
  one more line\
  yet another"                        # a string can span more than a single line.
  t = """A triple quoted string does  # another way of representing multiline strings.
  not need to be escaped at the end and
  "can have nested quotes" etc."""


  Try the following on the interpreter: 
          s = 'this is a string with 'quotes' of similar kind'


  Exercise: How to use single quotes within single quotes in a string as shown in the above example without getting an error?



  4.3.1. String operations
  A few basic string operations are presented here.

  String concatenation String concatenation is done by simple addition of two strings.
          
  &gt;&gt;&gt; x = 'Hello'
  &gt;&gt;&gt; y = ' Python'
  &gt;&gt;&gt; print x+y
  Hello Python


   Try this yourself:

  &gt;&gt;&gt; somenum = 13
  &gt;&gt;&gt; print x+somenum


  The problem with the above example is that here a string variable and an integer variable are trying to be concantenated. To obtain the desired result from the above example the str(), repr() and the `` can be used.

  str() simply converts a value to a string in a reasonable form. 
            repr() creates a string that is a representation of the value.
          
  The difference can be seen in the example shown below:
  &gt;&gt;&gt; str(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000'
  &gt;&gt;&gt; repr(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000L'


  It can be observed that the 'L' in the long value shown was omitted by str(), whereas repr() converted that into a string too. An alternative way of using repr(value) is `
            value`.
          
  A few more examples:
  &gt;&gt;&gt; x = "Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go 
  to Pycon


  In the above example, notice that the '\n'(newline) character is formatted and the string is printed on two lines. The strings discussed until now were normal strings. Other than these there are two other types of strings namely, raw strings and unicode strings.

  Raw strings are strings which are unformatted, that is the backslashes(\) are not parsed and are left as it is in the string. Raw strings are represented with an 'r' at the start of a string. Let us look at an example
          
  &gt;&gt;&gt; x = r"Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go \nto Pycon


  Note: The '\n' is not being parsed into a new line and is left as it is.

  Try this yourself:

  &gt;&gt;&gt; x = r"Let's go to Pycon\"


   Unicode strings are strings where the characters are Unicode characters as opposed to ASCII characters. Unicode strings are represented with a 'u' at the start of the string. Let us look at an example:
          
  &gt;&gt;&gt; x = u"Let's go to Pycon!"
  &gt;&gt;&gt; print x
  Let's go to Pycon!






  4.4. Boolean
  Python also provides special Boolean datatype. A boolean variable can assume a value of either 
          True or 
          False (Note the capitalizations).
        
  Let us look at examples:
  &gt;&gt;&gt; t = True
  &gt;&gt;&gt; f = not t
  &gt;&gt;&gt; print f
  False
  &gt;&gt;&gt; f or t
  True
  &gt;&gt;&gt; f and t
  False






  5. The 
        while loop
      
  The Python 
        while loop is similar to the C/C++ while loop. The syntax is as follows:
      
  statement 0
  while condition:
    statement 1 #while block
    statement 2 #while block
  statement 3 #outside the while block.


  Let us look at an example:
  &gt;&gt;&gt; x = 1  
  &gt;&gt;&gt; while x &lt;= 5:
  ...   print x
  ...   x += 1
  ... 
  1
  2
  3
  4
  5





  6. The 
        if conditional
      
  The Python 
        if block provides the conditional execution of statements. If the condition evaluates as true the block of statements defined under the if block are executed.
      
  If the first block is not executed on account of the condition not being satisfied, the set of statements in the 
        else block are executed.
      
  The 
        elif block provides the functionality of evaluation of multiple conditions as shown in the example.
      
  The syntax is as follows:
  if condition :
      statement_1
      statement_2

  elif condition:
      statement_3
      statement_4
  else:
      statement_5
      statement_6


  Let us look at an example:
  &gt;&gt;&gt; n = raw_input("Input a number:")
  &gt;&gt;&gt; if n &lt; 0:
        print n," is negative"
        elif n &gt; 0:
        print n," is positive"
        else:
        print n, " is 0"





  7.       raw_input()

  In the previous example we saw the call to the raw_input() subroutine. The 
        raw_input() method is used to take user inputs through the console. Unlike 
        input() which assumes the data entered by the user as a standard python expression, 
        raw_input() treats all the input data as raw data and converts everything into a string. To illustrate this let us look at an example.
      
  &gt;&gt;&gt; input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  121

  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:PythonFreak
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;string&gt;", line 1, in &lt;module&gt;
  NameError: name 'PythonFreak' is not defined


  As shown above the 
        input() assumes that the data entered is a valid Python expression. In the first call it prompts for an integer input and when entered it accepts the integer as an integer, whereas in the second call, when the string is entered without the quotes, 
        input() assumes that the entered data is a valid Python expression and hence it raises and exception saying PythonFreak is not defined.
      
  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:'PythonFreak'
  'PythonFreak'
  &gt;&gt;&gt; 


  Here the name is accepted because its entered as a string (within quotes). But its unreasonable to go on using quotes each time a string is entered. Hence the alternative is to use 
        raw_input().
      
  Let us now look at how 
        raw_input() operates with an example.
      
  &gt;&gt;&gt; raw_input("Enter your name:")
  Enter your name:PythonFreak
  'PythonFreak'


  Observe that the 
        raw_input() is converting it into a string all by itself.
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  '121'


  Observe that 
        raw_input() is converting the integer 121 also to a string as '121'. Let us look at another example:
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  &gt;&gt;&gt; pal + 2
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  TypeError: cannot concatenate 'str' and 'int' objects
  &gt;&gt;&gt; pal
  '121'


  Observe here that the variable 
        pal is a string and hence integer operations cannot be performed on it. Hence the exception is raised.
      



  8. 
        int() method
      
  Generally for computing purposes, the data used is not strings or raw data but on integers, floats and similar mathematical data structures. The data obtained from 
        raw_input() is raw data in the form of strings. In order to obtain integers from strings we use the method 
        int().
      
  Let us look at an example.
  &gt;&gt;&gt; intpal = int(pal)
  &gt;&gt;&gt; intpal
  121


  In the previous example it was observed that 
        pal was a string variable. Here using the 
        int() method the string 
        pal was converted to an integer variable.
      

  Try This Yourself:

  &gt;&gt;&gt; stringvar = raw_input("Enter a name:")
  Enter a name:Guido Van Rossum
  &gt;&gt;&gt; stringvar
  'Guido Van Rossum'
  &gt;&gt;&gt; numvar = int(stringvar)


url: localhost/review/html/ch03-session4.html
title: Chapter 1.
content:
  Table of Contents

  More text processing

  1. 
        uniq

  2.       join

  3. Generating a word frequency list
  4. Basic editing and editors

  4.1. vim
  4.2. SciTE

  5. Personalizing your Environment

  5.1. .bashrc
  5.2. .vimrc

  6. Subshells and 
        source







  More text processing



  Table of Contents

  1. 
        uniq

  2.       join

  3. Generating a word frequency list
  4. Basic editing and editors

  4.1. vim
  4.2. SciTE

  5. Personalizing your Environment

  5.1. .bashrc
  5.2. .vimrc

  6. Subshells and 
        source



  sortLet's say we have a file which lists a few of the stalwarts of the open source community and a few details about them, like their "other" name, their homepage address, and what they are well known for or their claim to fame.
  Richard Stallman%rms%GNU Project
  Eric Raymond%ESR%Jargon File
  Ian Murdock% %Debian
  Lawrence Lessig% %Creative Commons
  Linus Torvalds% %Linux Kernel
  Guido van Rossum%BDFL%Python
  Larry Wall% %Perl



  The sort command enables us to do this in a flash! Just running the sort command with the file name as a parameter sorts the lines of the file alphabetically and prints the output on the terminal. :
  $ sort stalwarts.txt 
  Eric Raymond%ESR%Jargon File
  Guido van Rossum%BDFL%Python
  Ian Murdock% %Debian
  Larry Wall% %Perl
  Lawrence Lessig% %Creative Commons
  Linus Torvalds% %Linux Kernel
  Richard Stallman%rms%GNU Project


  If you wish to sort them reverse alphabetically, you just need to pass the 
      -r option. Now, you might want to sort the lines, based on each person's claim to fame or their "other" name. What do we do in that case?
    
  Below is an example that sorts the file based on "other" names. :
  $ sort -t % -k 2,2  stalwarts.txt

  Ian Murdock% %Debian
  Larry Wall% %Perl
  Lawrence Lessig% %Creative Commons
  Linus Torvalds% %Linux Kernel
  Guido van Rossum%BDFL%Python
  Eric Raymond%ESR%Jargon File
  Richard Stallman%rms%GNU Project


  Sort command assumes white space to be the default delimiter for columns in each line. The 
      -t option specifies the delimiting character, which is 
      % in this case.
    
  The 
      -k option starts a key at position 2 and ends it at 2, essentially telling the sort command that it should sort based on the 2nd column, which is the other name. 
      sort also supports conflict resolution using multiple columns for sorting. You can see that the first three lines have nothing in the "other" names column. We could resolve the conflict by sorting based on the project names (the 3rd column).
    
  $ sort -t % -k 2,2 -k 3,3  stalwarts.txt

  Lawrence Lessig% %Creative Commons
  Ian Murdock% %Debian
  Linus Torvalds% %Linux Kernel
  Larry Wall% %Perl
  Guido van Rossum%BDFL%Python
  Eric Raymond%ESR%Jargon File
  Richard Stallman%rms%GNU Project


   sort also has a lot of other options like ignoring case differences, month sort(JAN&lt;FEB&lt;...), merging already sorted files. 
      man sort would give you a lot of information.
    


  1. 
        uniq

  Suppose we have a list of items, say books, and we wish to obtain a list which names of all the books only once, without any duplicates. We use the 
        uniq command to achieve this.
      
  Programming Pearls
  The C Programming Language
  The Mythical Man Month: Essays on Software Engineering 
  Programming Pearls
  The C Programming Language
  Structure and Interpretation of Computer Programs
  Programming Pearls
  Compilers: Principles, Techniques, and Tools
  The C Programming Language
  The Art of UNIX Programming
  Programming Pearls
  The Art of Computer Programming
  Introduction to Algorithms
  The Art of UNIX Programming
  The Pragmatic Programmer: From Journeyman to Master
  Programming Pearls
  Unix Power Tools
  The Art of UNIX Programming


  Let us try and get rid of the duplicate lines from this file using the 
        uniq command.
      
  $ uniq items.txt 
  Programming Pearls
  The C Programming Language
  The Mythical Man Month: Essays on Software Engineering 
  Programming Pearls
  The C Programming Language
  Structure and Interpretation of Computer Programs
  Programming Pearls
  Compilers: Principles, Techniques, and Tools
  The C Programming Language
  The Art of UNIX Programming
  Programming Pearls
  The Art of Computer Programming
  Introduction to Algorithms
  The Art of UNIX Programming
  The Pragmatic Programmer: From Journeyman to Master
  Programming Pearls
  Unix Power Tools
  The Art of UNIX Programming


  Nothing happens! Why? The 
        uniq command removes duplicate lines only when they are next to each other. So, we get a sorted file from the original file and work with that file, henceforth.
      
  $ sort items.txt &gt; items-sorted.txt
  $ uniq items-sorted.txt
  Compilers: Principles, Techniques, and Tools
  Introduction to Algorithms
  Programming Pearls
  Structure and Interpretation of Computer Programs
  The Art of Computer Programming
  The Art of UNIX Programming
  The C Programming Language
  The Mythical Man Month: Essays on Software Engineering 
  The Pragmatic Programmer: From Journeyman to Master
  Unix Power Tools


   uniq -u command gives the lines which are unique and do not have any duplicates in the file. 
        uniq -d outputs only those lines which have duplicates. The 
        -c option displays the number of times each line occurs in the file. :
      
  $ uniq -u items-sorted.txt 
  Compilers: Principles, Techniques, and Tools
  Introduction to Algorithms
  Structure and Interpretation of Computer Programs
  The Art of Computer Programming
  The Mythical Man Month: Essays on Software Engineering 
  The Pragmatic Programmer: From Journeyman to Master
  Unix Power Tools

  $ uniq -dc items-sorted.txt      
  5 Programming Pearls
  3 The Art of UNIX Programming
  3 The C Programming Language






  2.       join

  Now suppose we had the file 
        stalwarts1.txt, which lists the home pages of all the people listed in 
        stalwarts.txt. :
      
  Richard Stallman%http://www.stallman.org
  Eric Raymond%http://www.catb.org/~esr/
  Ian Murdock%http://ianmurdock.com/
  Lawrence Lessig%http://lessig.org
  Linus Torvalds%http://torvalds-family.blogspot.com/
  Guido van Rossum%http://www.python.org/~guido/
  Larry Wall%http://www.wall.org/~larry/


  It would be nice to have a single file with the information in both the files. To achieve this we use the 
        join command. :
      
  $ join stalwarts.txt stalwarts1.txt -t %
  Richard Stallman%rms%GNU Project%http://www.stallman.org
  Eric Raymond%ESR%Jargon File%http://www.catb.org/~esr/
  Ian Murdock% %Debian%http://ianmurdock.com/
  Lawrence Lessig% %Creative Commons%http://lessig.org
  Linus Torvalds% %Linux Kernel%http://torvalds-family.blogspot.com/
  Guido van Rossum%BDFL%Python%http://www.python.org/~guido/
  Larry Wall% %Perl%http://www.wall.org/~larry/


  The 
        join command joins the two files, based on the common field present in both the files, which is the name, in this case.
      
  The 
        -t option again specifies the delimiting character. Unless that is specified, join assumes that the fields are separated by spaces.
      
  Note that, for 
        join to work, the common field should be in the same order in both the files. If this is not so, you could use 
        sort, to sort the files on the common field and then join the files. In the above example, we have the common field to be the first column in both the files. If this is not the case we could use the 
        -1 and 
        -2 options to specify the field to be used for joining the files. :
      
  $ join -2 2 stalwarts.txt stalwarts2.txt -t %
  Richard Stallman%rms%GNU Project%http://www.stallman.org
  Eric Raymond%ESR%Jargon File%http://www.catb.org/~esr/
  Ian Murdock% %Debian%http://ianmurdock.com/
  Lawrence Lessig% %Creative Commons%http://lessig.org
  Linus Torvalds% %Linux Kernel%http://torvalds-family.blogspot.com/
  Guido van Rossum%BDFL%Python%http://www.python.org/~guido/
  Larry Wall% %Perl%http://www.wall.org/~larry/






  3. Generating a word frequency list
  Now, let us use the tools we have learnt to use, to generate a word frequency list of a text file. We shall use the free text of Alice in Wonderland.
  The basic steps to achieve this task would be -

  Eliminate the punctuation and spaces from the document.
  Generate a list of words.
  Count the words.

  We first use 
        grep and some elementary 
        regex to eliminate the non-alpha-characters. :
      
  $ grep "[A-Za-z]*" alice-in-wonderland.txt


  This outputs all the lines which has any alphabetic characters on it. This isn't of much use, since we haven't done anything with the code. We only require the alphabetic characters, without any of the other junk. 
        man grep shows us the 
        -o option for outputting only the text which matches the regular expression. :
      
  $ grep "[A-Za-z]*" -o alice-in-wonderland.txt


  Not very surprisingly, we have all the words, spit out in the form of a list! Now that we have a list of words, it is quite simple to count the occurrences of the words. You would've realized that we can make use of 
        sort and 
        uniq commands. We pipe the output from the 
        grep to the 
        sort and then pipe it's output to 
        uniq. :
      
  $ grep "[A-Za-z]*" -o alice-in-wonderland.txt | sort | uniq -c 


  Notice that you get the list of all words in the document in the alphabetical order, with it's frequency written next to it. But, you might have observed that Capitalized words and lower case words are being counted as different words. We therefore, replace all the Upper case characters with lower case ones, using the 
        tr command. :
      
  $ grep  "[A-Za-z]*" -o alice-in-wonderland.txt | tr 'A-Z' 'a-z' | sort | uniq -c 


  Now, it would also be nice to have the list ordered in the decreasing order of the frequency of the appearance of the words. We sort the output of the 
        uniq command with 
        -n and 
        -r options, to get the desired output. :
      
  $ grep  "[A-Za-z]*" -o alice-in-wonderland.txt | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr





  4. Basic editing and editors


  4.1. vim
  Vim is a very powerful editor. It has a lot of commands, and all of them cannot be explained here. We shall try and look at a few, so that you can find your way around in vim.
  To open a file in vim, we pass the filename as a parameter to the 
          vim command. If a file with that filename does not exist, a new file is created. :
        
  $ vim first.txt


  To start inserting text into the new file that we have opened, we need to press the 
          i key. This will take us into the 
          insert mode from the 
          command mode. Hitting the 
          esc key, will bring us back to the 
          command mode. There is also another mode of vim, called the 
          visual mode which will be discussed later in the course.
        
  In general, it is good to spend as little time as possible in the insert mode and extensively use the command mode to achieve various tasks.
  To save the file, use 
          :w in the command mode. From here on, it is understood that we are in the command mode, whenever we are issuing any command to vim.
        
  To save a file and continue editing, use 
          :w FILENAME The file name is optional. If you do not specify a filename, it is saved in the same file that you opened. If a file name different from the one you opened is specified, the text is saved with the new name, but you continue editing the file that you opened. The next time you save it without specifying a name, it gets saved with the name of the file that you initially opened.
        
  To save file with a new name and continue editing the new file, use 
          :saveas FILENAME

  To save and quit, use 
          :wq

  To quit, use 
          :q

  To quit without saving, use 
          :q!



  4.1.1. Moving around
  While you are typing in a file, it is in-convenient to keep moving your fingers from the standard position for typing to the arrow keys. Vim, therefore, provides alternate keys for moving in the document. Note again that, you should be in the command mode, when issuing any commands to vim.
  The basic cursor movement can be achieved using the keys, 
            h (left), 
            l (right), 
            k (up) and 
            j (down). :
          
  ^
  k              


  &lt; h       l &gt;


  j v


  Note: Most commands can be prefixed with a number, to repeat the command. For instance, 
            10j will move the cursor down 10 lines.
          


  4.1.1.1. Moving within a line







  Cursor Movement


  Command





  Beginning of line



  0





  First non-space character of line



  ^





  End of line



  $





  Last non-space character of line



  g_








  4.1.1.2. Moving by words and sentences







  Cursor Movement


  Command





  Forward, word beginning



  w





  Backward, word beginning



  b





  Forward, word end



  e





  Backward, word end



  ge





  Forward, sentence beginning



  )





  Backward, sentence beginning



  (





  Forward, paragraph beginning



  }





  Backward, paragraph beginning



  {








  4.1.1.3. More movement commands







  Cursor Movement


  Command





  Forward by a screenful of text



  C-f





  Backward by a screenful of text



  C-b





  Beginning of the screen



  H





  Middle of the screen



  M





  End of the screen



  L





  End of file



  G





  Line number 
                        num




  [num]G





  Beginning of file



  gg





  Next occurrence of the text under the cursor




  *







  Previous occurrence of the text under the cursor




  #







  Note: 
              C-x is 
              Ctrl + 
              x





  4.1.2. The visual mode
  The visual mode is a special mode that is not present in the original vi editor. It allows us to highlight text and perform actions on it. All the movement commands that have been discussed till now work in the visual mode also. The editing commands that will be discussed in the future work on the visual blocks selected, too.



  4.1.3. Editing commands
  The editing commands usually take the movements as arguments. A movement is equivalent to a selection in the visual mode. The cursor is assumed to have moved over the text in between the initial and the final points of the movement. The motion or the visual block that's been highlighted can be passed as arguments to the editing commands.







  Editing effect


  Command





  Cutting text



  d





  Copying/Yanking text



  y





  Pasting copied/cut text



  p





  The cut and copy commands take the motions or visual blocks as arguments and act on them. For instance, if you wish to delete the text from the current text position to the beginning of the next word, type 
            dw. If you wish to copy the text from the current position to the end of this sentence, type 
            y).
          
  Apart from the above commands, that take any motion or visual block as an argument, there are additional special commands.







  Editing effect


  Command





  Cut the character under the cursor



  x





  Replace the character under the cursor with 
                      a





  ra







  Cut an entire line



  dd





  Copy/yank an entire line



  yy





  Note: You can prefix numbers to any of the commands, to repeat them.



  4.1.4. Undo and Redo
  You can undo almost anything using 
            u.
          
  To undo the undo command type 
            C-r




  4.1.5. Searching and Replacing







  Finding


  Command





  Next occurrence of 
                      text, forward
                    



  \text





  Next occurrence of 
                      text, backward
                    



  ?text





  Search again in the same direction



  n





  Search again in the opposite direction



  N





  Next occurrence of 
                      x in the line
                    



  fx





  Previous occurrence of 
                      x in the line
                    



  Fx












  Finding and Replacing


  Command





  Replace the first instance of 
                      old with 
                      new in the current line.
                    



  :s/old/new





  Replace all instances of 
                      old with 
                      new in the current line.
                    



  :s/old/new/g





  Replace all instances of 
                      old with 
                      new in the current line, but ask for confirmation each time.
                    



  :s/old/new/gc





  Replace the first instance of 
                      old with 
                      new in the entire file.
                    



  :%s/old/new





  Replace all instances of 
                      old with 
                      new in the entire file.
                    



  :%s/old/new/g





  Replace all instances of 
                      old with 
                      new in the entire file but ask for confirmation each time.
                    



  :%s/old/new/gc









  4.2. SciTE
  SciTE is a 
          source code editor, that has a feel similar to the commonly used GUI text editors. It has a wide range of features that are extremely useful for a programmer, editing code. Also it aims to keep configuration simple, and the user needs to edit a text file to configure SciTE to his/her liking.
        
  Opening, Saving, Editing files with SciTE is extremely simple and trivial. Knowledge of using a text editor will suffice.
  SciTE can syntax highlight code in various languages. It also has auto-indentation, code-folding and other such features which are useful when editing code.
  SciTE also gives you the option to (compile and) run your code, from within the editor.




  5. Personalizing your Environment


  5.1. .bashrc
  What would you do, if you want bash to execute a particular command each time you start it up? For instance, say you want the current directory to be your Desktop instead of your home folder, each time bash starts up. How would you achieve this? Bash reads and executes commands in a whole bunch of files called start-up files, when it starts up.
  When bash starts up as an interactive login shell, it reads the files 
          /etc/profile, 
          ~/.bash_profile, 
          ~/.bash_login, and 
          ~/.profile in that order.
        
  When it is a shell that is not a login shell, 
          ~/.bashrc is read and the commands in it are executed. This can be prevented using the 
          --norc option. To force bash to use another file, instead of the 
          ~/.bashrc file on start-up, the 
          --rcfile option may be used.
        
  Now, you know what you should do, to change the current directory to you Desktop. Just put a 
          cd ~/Desktop into your 
          ~/.bashrc and you are set!
        
  This example is quite a simple and lame one. The start-up files are used for a lot more complex things than this. You could set (or unset) aliases and a whole bunch of environment variables in the 
          .bashrc. We shall look at them, in the next section where we look at environment variables and 
          set command.
        



  5.2. .vimrc

  .vimrc is a file similar to 
          .bashrc for vim. It is a start-up file that vim reads and executes, each time it starts up. The options that you would like to be set every time you use vim, are placed in the 
          .vimrc file, so that they are automatically set each time vim starts. The recommended place for having your 
          .vimrc is also your home directory.
        
  The file 
          /etc/vimrc is the global config file and shouldn't usually be edited. You can instead edit the 
          ~/.vimrc file that is present in your home folder.
        
  There are a whole bunch of variables that you could set in the 
          .vimrc file. You can look at all the options available, using the 
          :set all command in vim. You could use the 
          :help option_name to get more information about the option that you want to set. Once you are comfortable with what you want to set a particular variable to, you could add it to 
          .vimrc. You should also look at 
          :help vimrc for more info on the 
          .vimrc file. If you already have a 
          .vimrc file, you can edit it from within vim, using 
          :e $MYVIMRC command. We shall look at some of the most commonly used options.
        







  Command


  Vim action






  set nocompatible



  Explicitly disable compatibility with vi






  set backspace=indent,eol,start





  In the insert mode, vim allows the backspace key to delete white spaces at the start of line, line breaks and the character before which insert mode started.




  set autoindent


  Vim indents a new line with the same indentation of the previous line.




  set backup


  Vim keeps a backup copy of a file when overwriting it.




  set history=50


  Vim keeps 50 commands and 50 search patterns in the history.




  set ruler


  Displays the current cursor position in the lower right corner of the vim window.




  set showcmd


  Displays the incomplete command in the lower right corner.




  set incsearch


  Turns on incremental searching. Displays search results while you type.




  You can see the effect of the changes made to your 
          .vimrc file by restarting vim. If you want to see the changes that you made to your 
          .vimrc file immediately, you could source the file from within vim.
        
  If the 
          .vimrc file has been sourced when this instance of vim was started, you could just resource the file again:
        
  :so $MYVIMRC
  If you just created the 
          .vimrc file or it was not sourced when you stared this instance of vim, just replace the 
          $MYVIMRC variable above, with the location of the 
          .vimrc file that you created/edited.
        




  6. Subshells and 
        source

  A subshell is just a separate instance of the shell which is a child process of the shell that launches it. Bash creates a subshell in various circumstances. Creation of subshells allows the execution of various processes simultaneously.

  When an external command is executed, a new subshell is created. Any built-in commands of bash are executed with int the same shell, and no new subshell is started. When an external command is run, the bash shell copies itself (along with it's environment) creating a subshell and the process is changed to the external command executed. The subshell is a child process of this shell.
  Any pipes being used, create a subshell. The commands on the input and output ends of the pipe are run in different subshells.
  You could also, explicitly tell bash to start a subshell by enclosing a list of commands between parentheses. Each of the commands in the list is executed within a single new subshell.

  To avoid creating a subshell, when running a shell script, you could use the 
        source command. :
      
  $ source script.sh


  This will run the 
        script.sh within the present shell without creating a subshell. The 
        . command is an alias for the source command. 
        . script.sh is therefore equivalent to 
        source script.sh.
      


url: localhost/review/html/ch04-latex.html
title: Chapter 1.
content:
  Table of Contents

  Module 3: LaTeX

  1. Suggested Reading
  2. Session Level Split-up






  Module 3: LaTeX



  Table of Contents

  1. Suggested Reading
  2. Session Level Split-up

  Module Objectives
    After completing this module, a participant will be successfully able to:

  Produce professional documents in LaTeX.  RBT Ap
  Typeset Mathematical equations.           RBT Ap
  Include figures, tables and code samples. RBT Ap
  Add References and write BibTeX files.    RBT Ap



  1. Suggested Reading


  LaTeX Wikibook


  The Not So Short Introduction to LaTeX2e by Tobias Oetikar et. al.
          




  2. Session Level Split-up
  +---------+---------------------------------+---------+ | Session | Topic  			    | Duration| +=========+=================================+=========+ | 1	  | Introduction, TeX &amp; LaTeX       |  5 min  | |         | WYSIWG vs. WYSIWM               |         | |         |                                 |         | |         | Hello World, Compiling,         |  10 min | |         | Where we want to go, Some Basics|         | +---------+---------------------------------+---------+ | 2	  | Some Structural Elements        |  15 min | |         |                                 |         | |         | Top Matter, 
        \documentclass, |         | |	  | Abstract,                       |         | |         | Sections, Chapters &amp; Parts,     |         | |         | Appendices, Table of Contents   |         | +---------+---------------------------------+---------+ | 3	  | Emphasizing, Quotation marks,   |  5 min  | |	  | Dashes &amp; Hyphens, Footnotes,    |         | |         | Flushleft, Flushright &amp; Center  |         | |	  |                                 |         | |         | Enumerate, Itemize, Description,|  10 min | |         | Quote, Quotation and Verse,     |         | |         | Verbatim                        |         | +---------+---------------------------------+---------+ | 4	  | 
        \tabular environment,       |  20 min | |         | Importing Graphics, Floats,     |         | |         | Captions, List of Figures,      |         | |         | List of Tables, Cross References|         | +---------+---------------------------------+---------+ | 5	  | 
        \thebibliography            |  10 min | |         | environment, BibTeX             |         | +---------+---------------------------------+---------+ | 6	  | 
        \usepackage{amsmath},       |  5 min  | |         | Single Equations                |         | |         |                                 |         | |         | Building blocks of an equation, |  15 min | |         | Multiple Equations, Arrays and  |         | |	  | Matrices                        |         | +---------+---------------------------------+---------+ | 7       | 
        beamer, 
        listing,        |  10 min | |         | Including files                 |         | +---------+---------------------------------+---------+ | 8       | Exercises                       |  15 min | +---------+---------------------------------+---------+
      


url: localhost/review/html/ch02-oop.html
title: Classes and Objects
content:
  Classes and Objects


  In the previous sections we learnt about functions which provide certain level of abstraction to our code by holding the code which performs one or more specific functionalities. We were able to use this function as many times as we wanted. In addition to functions, Python also higher level of abstractions through 
      Classes and 
      Objects. 
      Objects can be loosely defined as a collection of a set of data items and a set of methods. The data items can be any valid Python variable or any Python object. Functions enclosed within a class are called as 
      methods. If you are thinking if methods are functions why is there a distinction between the two? The answer to this will be given as we walk through the concepts of 
      Classes and 
      Objects. 
      Classes contain the definition for the 
      Objects. 
      Objects are instances of 
      Classes.
    
  A class is defined using the keyword 
      class followed by the class name, in turn followed by a semicolon. The statements that a 
      Class encloses are written in a new block, i.e on the next indentation level:
    
  class Employee:
    def setName(self, name):
      self.name = name

    def getName(self):
      return self.name


  In the above example, we defined a class with the name Employee. We also defined two methods, setName and getName for this class. It is important to note the differences between the normal Python functions and class methods defined above. Each method of the class must take the same instance of the class(object) from which it was called as the first argument. It is conventionally given the name, 
      self. Note that 
      self is only a convention. You can use any other name, but the first argument to the method will always be the same object of the class from which the method was called. The data memebers that belong to the class are called as 
      class attributes. 
      Class attributes are preceded by the object of the class and a dot. In the above example, 
      name is a class attribute since it is preceded by the 
      self object. 
      Class attributes can be accessed from anywhere within the class.
    
  We can create objects of a class outside the class definition by using the same syntax we use to call a function with no parameters. We can assign this object to a variable:
  emp = Employee()


  In the above example, we create an object named 
      emp of the class 
      Employee. All the attributes and methods of the class can be accessed by the object of the class using the standard notation 
      object.attribute or 
      object.method(). Although the first parameter of a class method is the self object, it must not be passed as an argument when calling the method. The 
      self object is implicitly passed to the method by the Python interpreter. All other arguments passing rules like default arguments, keyword arguments, argument packing and unpacking follow the same rules as those for ordinary Python functions:
    
  &gt;&gt;&gt; emp.setName('John')
  &gt;&gt;&gt; name = emp.getName()
  &gt;&gt;&gt; print name
  John
  &gt;&gt;&gt; print emp.name
  John


  If we at all try to access a class attribute before assigning a value to it, i.e before creating it, Python raises the same error as it would raise for the accessing undefined variable:
  &gt;&gt;&gt; emp = Employee()
  &gt;&gt;&gt; emp.name
  Traceback (most recent call last):
    File "class.py", line 10, in &lt;module&gt;
      print e.name
  AttributeError: Employee instance has no attribute 'name'


url: localhost/review/html/ch01-intro.html
title: Basic Python
content:
  Basic Python



   
   



    -->










  Basic Python



  Table of Contents

  1. Introduction
  2. The Python Interpreter

  2.1. The Interactive Interpreter
  2.2. 
          ipython - An enhanced interactive Python interpreter
        

  3. Editing and running a python file
  4. Basic Datatypes and operators in Python

  4.1. Numbers
  4.2. Variables
  4.3. Strings
  4.4. Boolean

  5. The 
        while loop
      
  6. The 
        if conditional
      
  7.       raw_input()

  8. 
        int() method
      


  This document is intended to be handed out at the end of the workshop. It has been designed for Engineering students who are Python beginners and have basic programming skills. The focus is on basic numerics and plotting using Python.
  The system requirements:

  Python - version 2.5.x or newer.
  IPython
  Text editor - scite, vim, emacs or whatever you are comfortable with.



  1. Introduction
  The Python programming language was created by a dutch named Guido van Rossum. The idea of Python was conceived in December 1989. The name Python has nothing to do with the reptilian, but its been named after the 70s comedy series "Monty Python's Flying Circus", since it happens to be Guido's favourite TV series.
  Current stable version of Python is 2.6.x, although Python 3.0 is also the stable version, it is not backwards compatible with the previous versions and is hence not entirely popular at the moment. This material will focus on the 2.6.x series.
  Python is licensed under the Python Software Foundation License (PSF License) which is GPL compatible Free Software license (excepting license version 1.6 and 2.0) It is a no strings attached license, which means the source code is free to modify and redistribute.
  The Python docs define Python as "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics." A more detailed summary can be found at 
        http://www.python.org/doc/essays/blurb.html. Python is a language that has been designed to help the programmer concentrate on solving the problem at hand and not worry about the programming language idiosyncrasies.
      
  Python is a highly cross platform compatible language on account of it being an interpreted language. It is highly scalable and hence has been adapted to run on the Nokia 60 series phones. Python has been designed to be readable and easy to use

  Resources available for reference


  Web: 
            http://www.python.org

  Doc: 
            http://www.python.org/doc

  Free Tutorials: 
             Official Python Tutorial: 
              http://docs.python.org/tut/tut.html
   Byte of Python: 
            http://www.byteofpython.info/ * Dive into Python: 
            http://diveintopython.org/
          


  Advantages of Python - Why Python??


  Python has been designed for readability and ease of use. Its been designed in  such a fashion that it imposes readability on the programmer. Python does away with the braces and the semicolons and instead implements code blocks based on indentation, thus enhancing readability.
  Python is a high level, interpreted, modular and object oriented language. Python performs memory management on its own, thus the programmer need not bother about allocating and deallocating memory to variables. Python provides extensibility by providing modules which can be easily imported similar to headers in C and packages in Java. Python is object oriented and hence provides all the object oriented characteristics such as inheritance, encapsulation and polymorphism.
  Python offers a highly powerful interactive programming interface in the form of the 'Interactive Interpreter' which will be discussed in more detail in the following sections.
  Python provides a rich standard library and an extensive set of modules. The  power of Python modules can be seen in this slightly exaggerated cartoon 
            http://xkcd.com/353/
          
  Python interfaces well with most other programming languages such as C, C++  and FORTRAN.

  Although, Python has one setback. Python is not fast as some of the compiled languages like C or C++. Yet, the amount of flexibility and power more than make up for this setback.



  2. The Python Interpreter


  2.1. The Interactive Interpreter
  Typing 
          python at the shell prompt on any standard Unix/Gnu-Linux system and hitting the enter key fires up the Python 'Interactive Interpreter'. The Python interpreter is one of the most integral features of Python. The prompt obtained when the interactive interpreter is similar to what is shown below. The exact appearance might differ based on the version of Python being used. The 
          &gt;&gt;&gt; thing shown is the python prompt. When something is typed at the prompt and the enter key is hit, the python interpreter interprets the command entered and performs the appropriate action. All the examples presented in this document are to be tried hands on, on the interactive interpreter.
        
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  [GCC 4.3.2] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; 


  Lets try with an example, type 
          print 'Hello, World!' at the prompt and hit the enter key.
        
  &gt;&gt;&gt; print 'Hello, World!'
  Hello, World!


  This example was quite straight forward, and thus we have written our first line of Python code. Now let us try typing something arbitrary at the prompt. For example:
  &gt;&gt;&gt; arbit word
    File "&lt;stdin&gt;", line 1
      arbit word
              ^
  SyntaxError: invalid syntax
  &gt;&gt;&gt;


  The interpreter gave an error message saying that 'arbit word' was invalid syntax which is valid. The interpreter is an amazing tool when learning to program in Python. The interpreter provides a help function that provides the necessary documentation regarding all Python syntax, constructs, modules and objects. Typing 
          help() at the prompt gives the following output:
        
  &gt;&gt;&gt; help()

  Welcome to Python 2.5!  This is the online help utility.

  If this is your first time using Python, you should definitely check out
  the tutorial on the Internet at http://www.python.org/doc/tut/.

  Enter the name of any module, keyword, or topic to get help on writing
  Python programs and using Python modules.  To quit this help utility and
  return to the interpreter, just type "quit".

  To get a list of available modules, keywords, or topics, type "modules",
  "keywords", or "topics".  Each module also comes with a one-line summary
  of what it does; to list the modules whose summaries contain a given word
  such as "spam", type "modules spam".

  help&gt; 



  As mentioned in the output, entering the name of any module, keyword or topic will provide the documentation and help regarding the same through the online help utility. Pressing 
          Ctrl+d exits the help prompt and returns to the python prompt.
        
  Let us now try a few examples at the python interpreter.
  Eg 1:
  &gt;&gt;&gt; print 'Hello, python!'
  Hello, python!
  &gt;&gt;&gt;


  Eg 2:
  &gt;&gt;&gt; print 4321*567890
  2453852690
  &gt;&gt;&gt; 


  Eg 3:
  &gt;&gt;&gt; 4321*567890
  2453852690L
  &gt;&gt;&gt;


  Note: Notice the 'L' at the end of the output. The 'L' signifies that the
  output of the operation is of type *long*. It was absent in the previous
  example because we used the print statement. This is because *print* formats
  the output before displaying.


  Eg 4:
  &gt;&gt;&gt; big = 12345678901234567890 ** 3
  &gt;&gt;&gt; print big
  1881676372353657772490265749424677022198701224860897069000
  &gt;&gt;&gt; 


  This example is to show that unlike in C or C++ there is no limit on the
  value of an integer.


  Try this on the interactive interpreter: 
          import this


  Hint: The output gives an idea of Power of Python




  2.2. 
          ipython - An enhanced interactive Python interpreter
        
  The power and the importance of the interactive interpreter was the highlight of the previous section. This section provides insight into the enhanced interpreter with more advanced set of features called 
          ipython. Entering 
          ipython at the shell prompt fires up the interactive interpreter.
        
  $ ipython
  Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
  Type "copyright", "credits" or "license" for more information.

  IPython 0.8.4 -- An enhanced Interactive Python.
  ?         -&gt; Introduction and overview of IPython's features.
  %quickref -&gt; Quick reference.
  help      -&gt; Python's own help system.
  object?   -&gt; Details about 'object'. ?object also works, ?? prints more.

  In [1]: 


  This is the output obtained upon firing ipython. The exact appearance may change based on the Python version installed. The following are some of the various features provided by 
          ipython:
        




  Suggestions - ipython provides suggestions of the possible methods and operations available for the given python object.


  Eg 5:
  In [4]: a = 6

  In [5]: a.
  a.__abs__           a.__divmod__        a.__index__         a.__neg__          a.__rand__          a.__rmod__          a.__rxor__
  a.__add__           a.__doc__           a.__init__          a.__new__          a.__rdiv__          a.__rmul__          a.__setattr__
  a.__and__           a.__float__         a.__int__           a.__nonzero__      a.__rdivmod__       a.__ror__           a.__str__
  a.__class__         a.__floordiv__      a.__invert__        a.__oct__          a.__reduce__        a.__rpow__          a.__sub__
  a.__cmp__           a.__getattribute__  a.__long__          a.__or__           a.__reduce_ex__     a.__rrshift__       a.__truediv__
  a.__coerce__        a.__getnewargs__    a.__lshift__        a.__pos__          a.__repr__          a.__rshift__        a.__xor__
  a.__delattr__       a.__hash__          a.__mod__           a.__pow__          a.__rfloordiv__     a.__rsub__          
  a.__div__           a.__hex__           a.__mul__           a.__radd__         a.__rlshift__       a.__rtruediv__      


  In this example, we initialized 'a' (a variable - a concept that will be discussed in the subsequent sections.) to 6. In the next line when the 
          tab key is pressed after typing '
          a.' ipython displays the set of all possible methods that are applicable on the object 'a' (an integer in this context). Ipython provides many such datatype specific features which will be presented in the further sections as and when the datatypes are introduced.
        




  3. Editing and running a python file
  The previous sections focused on the use of the interpreter to run python code. While the interpeter is an excellent tool to test simple solutions and experiment with small code snippets, its main disadvantage is that everything written in the interpreter is lost once its quit. Most of the times a program is used by people other than the author. So the programs have to be available in some form suitable for distribution, and hence they are written in files. This section will focus on editing and running python files. Start by opening a text editor ( it is recommended you choose one from the list at the top of this page ). In the editor type down python code and save the file with an extension 
        .py (python files have an extension of .py). Once done with the editing, save the file and exit the editor.
      
  Let us look at a simple example of calculating the gcd of 2 numbers using Python:

  Creating the first python script(file) :
      
  $ emacs gcd.py
    def gcd(x,y):
      if x % y == 0:
        return y
      return gcd(y, x%y)

    print gcd(72, 92)


  To run the script, open the shell prompt, navigate to the directory that contains the python file and run 
        python &lt;filename.py&gt; at the prompt ( in this case filename is gcd.py )
      

  Running the python script :
      
  $ python gcd.py
  4
  $ 


  Another method to run a python script would be to include the line

  #! /usr/bin/python

  at the beginning of the python file and then make the file executable by
  $ chmod a+x 
        filename.py

  Once this is done, the script can be run as a standalone program as follows:
  $ ./
        filename.py




  4. Basic Datatypes and operators in Python
  Python provides the following set of basic datatypes.

  Numbers: int, float, long, complex
  Strings
  Boolean



  4.1. Numbers
  Numbers were introduced in the examples presented in the interactive interpreter section. Numbers include types as mentioned earlier viz., int (integers), float (floating point numbers), long (large integers), complex (complex numbers with real and imaginary parts). Python is not a strongly typed language, which means the type of a variable need not mentioned during its initialization. Let us look at a few examples.
  Eg 6:
  &gt;&gt;&gt; a = 1 #here a is an integer variable


  Eg 7:
  &gt;&gt;&gt; lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
  &gt;&gt;&gt; lng
  122333444455555666666777777788888888999999999L #notice the trailing 'L'
  &gt;&gt;&gt; print lng
  122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
  &gt;&gt;&gt; lng+1
  122333444455555666666777777788888889000000000L



  Long numbers are the same as integers in almost all aspects. They can be used in operations just like integers and along with integers without any distinction. The only distinction comes during type checking (which is not a healthy practice). Long numbers are tucked with a trailing 'L' just to signify that they are long. Notice that in the example just lng at the prompt displays the value of the variable with the 'L' whereas 
          print lng displays without the 'L'. This is because print formats the output before printing. Also in the example, notice that adding an integer to a long does not give any errors and the result is as expected. So for all practical purposes longs can be treated as ints.
        
  Eg 8:
  &gt;&gt;&gt; fl = 3.14159 #fl is a float variable
  &gt;&gt;&gt; e = 1.234e-4 #e is also a float variable, specified in the exponential form
  &gt;&gt;&gt; a = 1
  &gt;&gt;&gt; b = 2
  &gt;&gt;&gt; a/b #integer division
  0
  &gt;&gt;&gt; a/fl #floating point division
  0.31831015504887655
  &gt;&gt;&gt; e/fl
  3.9279473133031364e-05



  Floating point numbers, simply called floats are real numbers with a decimal point. The example above shows the initialization of a float variable. Shown also in this example is the difference between integer division and floating point division. 'a' and 'b' here are integer variables and hence the division gives 0 as the quotient. When either of the operands is a float, the operation is a floating point division, and the result is also a float as illustrated.
  Eg 9:
  &gt;&gt;&gt; cplx = 3 + 4j #cplx is a complex variable
  &gt;&gt;&gt; cplx
  (3+4j)
  &gt;&gt;&gt; print cplx.real #prints the real part of the complex number
  3.0
  &gt;&gt;&gt; print cplx.imag #prints the imaginary part of the complex number
  4.0
  &gt;&gt;&gt; print cplx*fl  #multiplies the real and imag parts of the complex number with the multiplier
  (9.42477+12.56636j)
  &gt;&gt;&gt; abs(cplx) #returns the absolute value of the complex number
  5.0


  Python provides a datatype for complex numbers. Complex numbers are initialized as shown in the example above. The 
          real and 
          imag operators return the real and imaginary parts of the complex number as shown. The 
          abs() returns the absolute value of the complex number.
        



  4.2. Variables
  Variables are just names that represent a value. Variables have already been introduced in the various examples from the previous sections. Certain rules about using variables:

  Variables have to be initialized or assigned a value before being used.
  Variable names can consist of letters, digits and 
                underscores .
              
  Variable names cannot begin with digits, but can contain digits in them.

  In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' are all variables of various datatypes.
  Note: Python is not a strongly typed language and hence an integer variable can at a
  later stage be used as a float variable as well.





  4.3. Strings
  Strings are one of the essential data structures of any programming language. The 
          print "Hello, World!" program was introduced in the earlier section, and the 
          "Hello, World!" in the print statement is a string. A string is basically a set of characters. Strings can be represented in various ways shown below:
        
  s = 'this is a string'              # a string variable can be represented using single quotes
  s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
  s = "I have 'single-quotes' inside!"
  l = "A string spanning many lines\
  one more line\
  yet another"                        # a string can span more than a single line.
  t = """A triple quoted string does  # another way of representing multiline strings.
  not need to be escaped at the end and
  "can have nested quotes" etc."""


  Try the following on the interpreter: 
          s = 'this is a string with 'quotes' of similar kind'


  Exercise: How to use single quotes within single quotes in a string as shown in the above example without getting an error?



  4.3.1. String operations
  A few basic string operations are presented here.

  String concatenation String concatenation is done by simple addition of two strings.
          
  &gt;&gt;&gt; x = 'Hello'
  &gt;&gt;&gt; y = ' Python'
  &gt;&gt;&gt; print x+y
  Hello Python


   Try this yourself:

  &gt;&gt;&gt; somenum = 13
  &gt;&gt;&gt; print x+somenum


  The problem with the above example is that here a string variable and an integer variable are trying to be concantenated. To obtain the desired result from the above example the str(), repr() and the `` can be used.

  str() simply converts a value to a string in a reasonable form. 
            repr() creates a string that is a representation of the value.
          
  The difference can be seen in the example shown below:
  &gt;&gt;&gt; str(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000'
  &gt;&gt;&gt; repr(1000000000000000000000000000000000000000000000000L)
  '1000000000000000000000000000000000000000000000000L'


  It can be observed that the 'L' in the long value shown was omitted by str(), whereas repr() converted that into a string too. An alternative way of using repr(value) is `
            value`.
          
  A few more examples:
  &gt;&gt;&gt; x = "Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go 
  to Pycon


  In the above example, notice that the '\n'(newline) character is formatted and the string is printed on two lines. The strings discussed until now were normal strings. Other than these there are two other types of strings namely, raw strings and unicode strings.

  Raw strings are strings which are unformatted, that is the backslashes(\) are not parsed and are left as it is in the string. Raw strings are represented with an 'r' at the start of a string. Let us look at an example
          
  &gt;&gt;&gt; x = r"Let's go \nto Pycon"
  &gt;&gt;&gt; print x
  Let's go \nto Pycon


  Note: The '\n' is not being parsed into a new line and is left as it is.

  Try this yourself:

  &gt;&gt;&gt; x = r"Let's go to Pycon\"


   Unicode strings are strings where the characters are Unicode characters as opposed to ASCII characters. Unicode strings are represented with a 'u' at the start of the string. Let us look at an example:
          
  &gt;&gt;&gt; x = u"Let's go to Pycon!"
  &gt;&gt;&gt; print x
  Let's go to Pycon!






  4.4. Boolean
  Python also provides special Boolean datatype. A boolean variable can assume a value of either 
          True or 
          False (Note the capitalizations).
        
  Let us look at examples:
  &gt;&gt;&gt; t = True
  &gt;&gt;&gt; f = not t
  &gt;&gt;&gt; print f
  False
  &gt;&gt;&gt; f or t
  True
  &gt;&gt;&gt; f and t
  False






  5. The 
        while loop
      
  The Python 
        while loop is similar to the C/C++ while loop. The syntax is as follows:
      
  statement 0
  while condition:
    statement 1 #while block
    statement 2 #while block
  statement 3 #outside the while block.


  Let us look at an example:
  &gt;&gt;&gt; x = 1  
  &gt;&gt;&gt; while x &lt;= 5:
  ...   print x
  ...   x += 1
  ... 
  1
  2
  3
  4
  5





  6. The 
        if conditional
      
  The Python 
        if block provides the conditional execution of statements. If the condition evaluates as true the block of statements defined under the if block are executed.
      
  If the first block is not executed on account of the condition not being satisfied, the set of statements in the 
        else block are executed.
      
  The 
        elif block provides the functionality of evaluation of multiple conditions as shown in the example.
      
  The syntax is as follows:
  if condition :
      statement_1
      statement_2

  elif condition:
      statement_3
      statement_4
  else:
      statement_5
      statement_6


  Let us look at an example:
  &gt;&gt;&gt; n = raw_input("Input a number:")
  &gt;&gt;&gt; if n &lt; 0:
        print n," is negative"
        elif n &gt; 0:
        print n," is positive"
        else:
        print n, " is 0"





  7.       raw_input()

  In the previous example we saw the call to the raw_input() subroutine. The 
        raw_input() method is used to take user inputs through the console. Unlike 
        input() which assumes the data entered by the user as a standard python expression, 
        raw_input() treats all the input data as raw data and converts everything into a string. To illustrate this let us look at an example.
      
  &gt;&gt;&gt; input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  121

  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:PythonFreak
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;string&gt;", line 1, in &lt;module&gt;
  NameError: name 'PythonFreak' is not defined


  As shown above the 
        input() assumes that the data entered is a valid Python expression. In the first call it prompts for an integer input and when entered it accepts the integer as an integer, whereas in the second call, when the string is entered without the quotes, 
        input() assumes that the entered data is a valid Python expression and hence it raises and exception saying PythonFreak is not defined.
      
  &gt;&gt;&gt; input("Enter your name:")
  Enter your name:'PythonFreak'
  'PythonFreak'
  &gt;&gt;&gt; 


  Here the name is accepted because its entered as a string (within quotes). But its unreasonable to go on using quotes each time a string is entered. Hence the alternative is to use 
        raw_input().
      
  Let us now look at how 
        raw_input() operates with an example.
      
  &gt;&gt;&gt; raw_input("Enter your name:")
  Enter your name:PythonFreak
  'PythonFreak'


  Observe that the 
        raw_input() is converting it into a string all by itself.
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  '121'


  Observe that 
        raw_input() is converting the integer 121 also to a string as '121'. Let us look at another example:
      
  &gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
  Enter a number thats a palindrome:121
  &gt;&gt;&gt; pal + 2
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  TypeError: cannot concatenate 'str' and 'int' objects
  &gt;&gt;&gt; pal
  '121'


  Observe here that the variable 
        pal is a string and hence integer operations cannot be performed on it. Hence the exception is raised.
      



  8. 
        int() method
      
  Generally for computing purposes, the data used is not strings or raw data but on integers, floats and similar mathematical data structures. The data obtained from 
        raw_input() is raw data in the form of strings. In order to obtain integers from strings we use the method 
        int().
      
  Let us look at an example.
  &gt;&gt;&gt; intpal = int(pal)
  &gt;&gt;&gt; intpal
  121


  In the previous example it was observed that 
        pal was a string variable. Here using the 
        int() method the string 
        pal was converted to an integer variable.
      

  Try This Yourself:

  &gt;&gt;&gt; stringvar = raw_input("Enter a name:")
  Enter a name:Guido Van Rossum
  &gt;&gt;&gt; stringvar
  'Guido Van Rossum'
  &gt;&gt;&gt; numvar = int(stringvar)









  Prev 
   
   


  Chapter 1. Introduction 
  Home
   


