web/html/ch01-intro.html~
changeset 0 8083d21c0020
equal deleted inserted replaced
-1:000000000000 0:8083d21c0020
       
     1 <html>
       
     2 <head>
       
     3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       
     4 <title>Basic Python</title>
       
     5 <link rel="stylesheet" href="/review/support/styles.css" type="text/css">
       
     6 <meta name="generator" content="DocBook XSL Stylesheets V1.74.3">
       
     7 <link rel="shortcut icon" type="image/png" href="/review/support/figs/favicon.png">
       
     8 <script type="text/javascript" src="/review/support/jquery-min.js"></script>
       
     9 <script type="text/javascript" src="/review/support/form.js"></script>
       
    10 <script type="text/javascript" src="/review/support/hsbook.js"></script>
       
    11 </head>
       
    12 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
       
    13 <!--<div class="navheader">
       
    14 <table width="100%" summary="Navigation header">
       
    15 <tr><th colspan="3" align="center">Basic Python</th></tr>
       
    16 <tr>
       
    17 <td width="20%" align="left">
       
    18 
       
    19 <th width="60%" align="center"> </th>
       
    20 <td width="20%" align="right"> </td>
       
    21 </tr>
       
    22 </table>
       
    23 <hr>
       
    24 </div>  -->
       
    25 <div>
       
    26 	<form style="margin-left: 800" method="POST" action="/review/hello">
       
    27 		<input id="id_q" type="text" name="q"/>
       
    28 		<input type="submit" value="Go"/>
       
    29 	</form>
       
    30 </div>
       
    31 
       
    32 <div class="chapter" lang="en" id="chap_intro">
       
    33 <div class="article" title="Basic Python">
       
    34 <div class="titlepage">
       
    35 <div><div><h2 class="title">
       
    36 <a name="id2988867"></a>Basic Python</h2></div></div>
       
    37 <hr>
       
    38 </div>
       
    39 <div class="toc">
       
    40 <p><b>Table of Contents</b></p>
       
    41 <dl>
       
    42 <dt><span class="section"><a href="#introduction">1. Introduction</a></span></dt>
       
    43 <dt><span class="section"><a href="#the-python-interpreter">2. The Python Interpreter</a></span></dt>
       
    44 <dd><dl>
       
    45 <dt><span class="section"><a href="#the-interactive-interpreter">2.1. The Interactive Interpreter</a></span></dt>
       
    46 <dt><span class="section"><a href="#ipython-an-enhanced-interactive-python-interpreter">2.2. 
       
    47         <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter
       
    48       </a></span></dt>
       
    49 </dl></dd>
       
    50 <dt><span class="section"><a href="#editing-and-running-a-python-file">3. Editing and running a python file</a></span></dt>
       
    51 <dt><span class="section"><a href="#basic-datatypes-and-operators-in-python">4. Basic Datatypes and operators in Python</a></span></dt>
       
    52 <dd><dl>
       
    53 <dt><span class="section"><a href="#numbers">4.1. Numbers</a></span></dt>
       
    54 <dt><span class="section"><a href="#variables">4.2. Variables</a></span></dt>
       
    55 <dt><span class="section"><a href="#strings">4.3. Strings</a></span></dt>
       
    56 <dt><span class="section"><a href="#boolean">4.4. Boolean</a></span></dt>
       
    57 </dl></dd>
       
    58 <dt><span class="section"><a href="#the-while-loop">5. The 
       
    59       <span class="strong"><strong>while</strong></span> loop
       
    60     </a></span></dt>
       
    61 <dt><span class="section"><a href="#the-if-conditional">6. The 
       
    62       <span class="strong"><strong>if</strong></span> conditional
       
    63     </a></span></dt>
       
    64 <dt><span class="section"><a href="#raw_input">7.       <span class="strong"><strong>raw_input()</strong></span>
       
    65     </a></span></dt>
       
    66 <dt><span class="section"><a href="#int-method">8. 
       
    67       <span class="strong"><strong>int()</strong></span> method
       
    68     </a></span></dt>
       
    69 </dl>
       
    70 </div>
       
    71 <p id="x_38"></a>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.</p>
       
    72 <p id="x_39"></a>The system requirements:</p>
       
    73 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
    74 <li class="listitem" style="list-style-type: *"><p id="x_3a"></a>Python - version 2.5.x or newer.</p></li>
       
    75 <li class="listitem" style="list-style-type: *"><p id="x_3b"></a>IPython</p></li>
       
    76 <li class="listitem" style="list-style-type: *"><p id="x_3c"></a>Text editor - scite, vim, emacs or whatever you are comfortable with.</p></li>
       
    77 </ul></div>
       
    78 <div class="section" title="1. Introduction">
       
    79 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
    80 <a name="introduction"></a>1. Introduction</h2></div></div></div>
       
    81 <p id="x_3d"></a>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.</p>
       
    82 <p id="x_3e"></a>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.</p>
       
    83 <p id="x_3f"></a>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.</p>
       
    84 <p id="x_40"></a>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 
       
    85       <a class="ulink" href="http://www.python.org/doc/essays/blurb.html" target="_top">http://www.python.org/doc/essays/blurb.html</a>. 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.
       
    86     </p>
       
    87 <p id="x_41"></a>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</p>
       
    88 <p id="x_42"></a>
       
    89       <span class="strong"><strong>Resources available for reference</strong></span>
       
    90     </p>
       
    91 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
    92 <li class="listitem" style="list-style-type: *"><p id="x_43"></a>Web: 
       
    93           <a class="ulink" href="http://www.python.org" target="_top">http://www.python.org</a>
       
    94         </p></li>
       
    95 <li class="listitem" style="list-style-type: *"><p id="x_44"></a>Doc: 
       
    96           <a class="ulink" href="http://www.python.org/doc" target="_top">http://www.python.org/doc</a>
       
    97         </p></li>
       
    98 <li class="listitem" style="list-style-type: *"><p id="x_45"></a>Free Tutorials: 
       
    99           <span class="emphasis"><em> Official Python Tutorial: 
       
   100             <a class="ulink" href="http://docs.python.org/tut/tut.html" target="_top">http://docs.python.org/tut/tut.html</a> 
       
   101           </em></span> Byte of Python: 
       
   102           <a class="ulink" href="http://www.byteofpython.info" target="_top">http://www.byteofpython.info</a>/ * Dive into Python: 
       
   103           <a class="ulink" href="http://diveintopython.org" target="_top">http://diveintopython.org</a>/
       
   104         </p></li>
       
   105 </ul></div>
       
   106 <p id="x_46"></a>
       
   107       <span class="strong"><strong>Advantages of Python - Why Python??</strong></span>
       
   108     </p>
       
   109 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
   110 <li class="listitem" style="list-style-type: *"><p id="x_47"></a>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.</p></li>
       
   111 <li class="listitem" style="list-style-type: *"><p id="x_48"></a>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.</p></li>
       
   112 <li class="listitem" style="list-style-type: *"><p id="x_49"></a>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.</p></li>
       
   113 <li class="listitem" style="list-style-type: *"><p id="x_4a"></a>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 
       
   114           <a class="ulink" href="http://xkcd.com/353" target="_top">http://xkcd.com/353</a>/
       
   115         </p></li>
       
   116 <li class="listitem" style="list-style-type: *"><p id="x_4b"></a>Python interfaces well with most other programming languages such as C, C++  and FORTRAN.</p></li>
       
   117 </ul></div>
       
   118 <p id="x_4c"></a>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.</p>
       
   119 </div>
       
   120 <div class="section" title="2. The Python Interpreter">
       
   121 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   122 <a name="the-python-interpreter"></a>2. The Python Interpreter</h2></div></div></div>
       
   123 <div class="section" title="2.1. The Interactive Interpreter">
       
   124 <div class="titlepage"><div><div><h3 class="title">
       
   125 <a name="the-interactive-interpreter"></a>2.1. The Interactive Interpreter</h3></div></div></div>
       
   126 <p id="x_4d"></a>Typing 
       
   127         <span class="emphasis"><em>python</em></span> 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 
       
   128         <code class="literal">&gt;&gt;&gt;</code> 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.
       
   129       </p>
       
   130 <pre class="programlisting">Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
       
   131 [GCC 4.3.2] on linux2
       
   132 Type "help", "copyright", "credits" or "license" for more information.
       
   133 &gt;&gt;&gt; 
       
   134 
       
   135 </pre>
       
   136 <p id="x_4e"></a>Lets try with an example, type 
       
   137         <code class="literal">print 'Hello, World!'</code> at the prompt and hit the enter key.
       
   138       </p>
       
   139 <pre class="programlisting">&gt;&gt;&gt; print 'Hello, World!'
       
   140 Hello, World!
       
   141 
       
   142 </pre>
       
   143 <p id="x_4f"></a>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:</p>
       
   144 <pre class="programlisting">&gt;&gt;&gt; arbit word
       
   145   File "&lt;stdin&gt;", line 1
       
   146     arbit word
       
   147             ^
       
   148 SyntaxError: invalid syntax
       
   149 &gt;&gt;&gt;
       
   150 
       
   151 </pre>
       
   152 <p id="x_50"></a>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 
       
   153         <span class="emphasis"><em>help()</em></span> at the prompt gives the following output:
       
   154       </p>
       
   155 <pre class="programlisting">&gt;&gt;&gt; help()
       
   156 
       
   157 Welcome to Python 2.5!  This is the online help utility.
       
   158 
       
   159 If this is your first time using Python, you should definitely check out
       
   160 the tutorial on the Internet at http://www.python.org/doc/tut/.
       
   161 
       
   162 Enter the name of any module, keyword, or topic to get help on writing
       
   163 Python programs and using Python modules.  To quit this help utility and
       
   164 return to the interpreter, just type "quit".
       
   165 
       
   166 To get a list of available modules, keywords, or topics, type "modules",
       
   167 "keywords", or "topics".  Each module also comes with a one-line summary
       
   168 of what it does; to list the modules whose summaries contain a given word
       
   169 such as "spam", type "modules spam".
       
   170 
       
   171 help&gt; 
       
   172 
       
   173 
       
   174 </pre>
       
   175 <p id="x_51"></a>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 
       
   176         <span class="emphasis"><em>Ctrl+d</em></span> exits the help prompt and returns to the python prompt.
       
   177       </p>
       
   178 <p id="x_52"></a>Let us now try a few examples at the python interpreter.</p>
       
   179 <p id="x_53"></a>Eg 1:</p>
       
   180 <pre class="programlisting">&gt;&gt;&gt; print 'Hello, python!'
       
   181 Hello, python!
       
   182 &gt;&gt;&gt;
       
   183 
       
   184 </pre>
       
   185 <p id="x_54"></a>Eg 2:</p>
       
   186 <pre class="programlisting">&gt;&gt;&gt; print 4321*567890
       
   187 2453852690
       
   188 &gt;&gt;&gt; 
       
   189 
       
   190 </pre>
       
   191 <p id="x_55"></a>Eg 3:</p>
       
   192 <pre class="programlisting">&gt;&gt;&gt; 4321*567890
       
   193 2453852690L
       
   194 &gt;&gt;&gt;
       
   195 
       
   196 </pre>
       
   197 <pre class="programlisting">Note: Notice the 'L' at the end of the output. The 'L' signifies that the
       
   198 output of the operation is of type *long*. It was absent in the previous
       
   199 example because we used the print statement. This is because *print* formats
       
   200 the output before displaying.
       
   201 
       
   202 </pre>
       
   203 <p id="x_56"></a>Eg 4:</p>
       
   204 <pre class="programlisting">&gt;&gt;&gt; big = 12345678901234567890 ** 3
       
   205 &gt;&gt;&gt; print big
       
   206 1881676372353657772490265749424677022198701224860897069000
       
   207 &gt;&gt;&gt; 
       
   208 
       
   209 </pre>
       
   210 <pre class="programlisting">This example is to show that unlike in C or C++ there is no limit on the
       
   211 value of an integer.
       
   212 
       
   213 </pre>
       
   214 <p id="x_57"></a>Try this on the interactive interpreter: 
       
   215         <code class="literal">import this</code>
       
   216       </p>
       
   217 <p id="x_58"></a>
       
   218         <span class="emphasis"><em>Hint: The output gives an idea of Power of Python</em></span>
       
   219       </p>
       
   220 </div>
       
   221 <div class="section" title="2.2.  ipython - An enhanced interactive Python interpreter">
       
   222 <div class="titlepage"><div><div><h3 class="title">
       
   223 <a name="ipython-an-enhanced-interactive-python-interpreter"></a>2.2. 
       
   224         <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter
       
   225       </h3></div></div></div>
       
   226 <p id="x_59"></a>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 
       
   227         <span class="strong"><strong>ipython</strong></span>. Entering 
       
   228         <span class="emphasis"><em>ipython</em></span> at the shell prompt fires up the interactive interpreter.
       
   229       </p>
       
   230 <pre class="programlisting">$ ipython
       
   231 Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
       
   232 Type "copyright", "credits" or "license" for more information.
       
   233 
       
   234 IPython 0.8.4 -- An enhanced Interactive Python.
       
   235 ?         -&gt; Introduction and overview of IPython's features.
       
   236 %quickref -&gt; Quick reference.
       
   237 help      -&gt; Python's own help system.
       
   238 object?   -&gt; Details about 'object'. ?object also works, ?? prints more.
       
   239 
       
   240 In [1]: 
       
   241 
       
   242 </pre>
       
   243 <p id="x_5a"></a>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 
       
   244         <span class="strong"><strong>ipython</strong></span>:
       
   245       </p>
       
   246 <div class="variablelist"><dl>
       
   247 <dt><span class="term"></span></dt>
       
   248 <dd>
       
   249 <p></p>
       
   250 <p id="x_5b"></a>Suggestions - ipython provides suggestions of the possible methods and operations available for the given python object.</p>
       
   251 </dd>
       
   252 </dl></div>
       
   253 <p id="x_5c"></a>Eg 5:</p>
       
   254 <pre class="programlisting">In [4]: a = 6
       
   255 
       
   256 In [5]: a.
       
   257 a.__abs__           a.__divmod__        a.__index__         a.__neg__          a.__rand__          a.__rmod__          a.__rxor__
       
   258 a.__add__           a.__doc__           a.__init__          a.__new__          a.__rdiv__          a.__rmul__          a.__setattr__
       
   259 a.__and__           a.__float__         a.__int__           a.__nonzero__      a.__rdivmod__       a.__ror__           a.__str__
       
   260 a.__class__         a.__floordiv__      a.__invert__        a.__oct__          a.__reduce__        a.__rpow__          a.__sub__
       
   261 a.__cmp__           a.__getattribute__  a.__long__          a.__or__           a.__reduce_ex__     a.__rrshift__       a.__truediv__
       
   262 a.__coerce__        a.__getnewargs__    a.__lshift__        a.__pos__          a.__repr__          a.__rshift__        a.__xor__
       
   263 a.__delattr__       a.__hash__          a.__mod__           a.__pow__          a.__rfloordiv__     a.__rsub__          
       
   264 a.__div__           a.__hex__           a.__mul__           a.__radd__         a.__rlshift__       a.__rtruediv__      
       
   265 
       
   266 </pre>
       
   267 <p id="x_5d"></a>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 
       
   268         <span class="emphasis"><em>tab</em></span> key is pressed after typing '
       
   269         <span class="emphasis"><em>a.</em></span>' 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.
       
   270       </p>
       
   271 </div>
       
   272 </div>
       
   273 <div class="section" title="3. Editing and running a python file">
       
   274 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   275 <a name="editing-and-running-a-python-file"></a>3. Editing and running a python file</h2></div></div></div>
       
   276 <p id="x_5e"></a>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 
       
   277       <span class="strong"><strong>.py</strong></span> (python files have an extension of .py). Once done with the editing, save the file and exit the editor.
       
   278     </p>
       
   279 <p id="x_5f"></a>Let us look at a simple example of calculating the gcd of 2 numbers using Python:</p>
       
   280 <p id="x_60"></a>
       
   281       <span class="strong"><strong>Creating the first python script(file)</strong></span> :
       
   282     </p>
       
   283 <pre class="programlisting">$ emacs gcd.py
       
   284   def gcd(x,y):
       
   285     if x % y == 0:
       
   286       return y
       
   287     return gcd(y, x%y)
       
   288 
       
   289   print gcd(72, 92)
       
   290 
       
   291 </pre>
       
   292 <p id="x_61"></a>To run the script, open the shell prompt, navigate to the directory that contains the python file and run 
       
   293       <code class="literal">python &lt;filename.py&gt;</code> at the prompt ( in this case filename is gcd.py )
       
   294     </p>
       
   295 <p id="x_62"></a>
       
   296       <span class="strong"><strong>Running the python script</strong></span> :
       
   297     </p>
       
   298 <pre class="programlisting">$ python gcd.py
       
   299 4
       
   300 $ 
       
   301 
       
   302 </pre>
       
   303 <p id="x_63"></a>Another method to run a python script would be to include the line</p>
       
   304 <p id="x_64"></a>
       
   305       <code class="literal">#! /usr/bin/python</code>
       
   306     </p>
       
   307 <p id="x_65"></a>at the beginning of the python file and then make the file executable by</p>
       
   308 <p id="x_66"></a>$ chmod a+x 
       
   309       <span class="emphasis"><em>filename.py</em></span>
       
   310     </p>
       
   311 <p id="x_67"></a>Once this is done, the script can be run as a standalone program as follows:</p>
       
   312 <p id="x_68"></a>$ ./
       
   313       <span class="emphasis"><em>filename.py</em></span>
       
   314     </p>
       
   315 </div>
       
   316 <div class="section" title="4. Basic Datatypes and operators in Python">
       
   317 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   318 <a name="basic-datatypes-and-operators-in-python"></a>4. Basic Datatypes and operators in Python</h2></div></div></div>
       
   319 <p id="x_69"></a>Python provides the following set of basic datatypes.</p>
       
   320 <div class="blockquote"><blockquote class="blockquote"><div class="itemizedlist"><ul class="itemizedlist" type="*">
       
   321 <li class="listitem" style="list-style-type: *"><p id="x_6a"></a>Numbers: int, float, long, complex</p></li>
       
   322 <li class="listitem" style="list-style-type: *"><p id="x_6b"></a>Strings</p></li>
       
   323 <li class="listitem" style="list-style-type: *"><p id="x_6c"></a>Boolean</p></li>
       
   324 </ul></div></blockquote></div>
       
   325 <div class="section" title="4.1. Numbers">
       
   326 <div class="titlepage"><div><div><h3 class="title">
       
   327 <a name="numbers"></a>4.1. Numbers</h3></div></div></div>
       
   328 <p id="x_6d"></a>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.</p>
       
   329 <p id="x_6e"></a>Eg 6:</p>
       
   330 <pre class="programlisting">&gt;&gt;&gt; a = 1 #here a is an integer variable
       
   331 
       
   332 </pre>
       
   333 <p id="x_6f"></a>Eg 7:</p>
       
   334 <pre class="programlisting">&gt;&gt;&gt; lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
       
   335 &gt;&gt;&gt; lng
       
   336 122333444455555666666777777788888888999999999L #notice the trailing 'L'
       
   337 &gt;&gt;&gt; print lng
       
   338 122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
       
   339 &gt;&gt;&gt; lng+1
       
   340 122333444455555666666777777788888889000000000L
       
   341 
       
   342 
       
   343 </pre>
       
   344 <p id="x_70"></a>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 
       
   345         <code class="literal">print lng</code> 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.
       
   346       </p>
       
   347 <p id="x_71"></a>Eg 8:</p>
       
   348 <pre class="programlisting">&gt;&gt;&gt; fl = 3.14159 #fl is a float variable
       
   349 &gt;&gt;&gt; e = 1.234e-4 #e is also a float variable, specified in the exponential form
       
   350 &gt;&gt;&gt; a = 1
       
   351 &gt;&gt;&gt; b = 2
       
   352 &gt;&gt;&gt; a/b #integer division
       
   353 0
       
   354 &gt;&gt;&gt; a/fl #floating point division
       
   355 0.31831015504887655
       
   356 &gt;&gt;&gt; e/fl
       
   357 3.9279473133031364e-05
       
   358 
       
   359 
       
   360 </pre>
       
   361 <p id="x_72"></a>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.</p>
       
   362 <p id="x_73"></a>Eg 9:</p>
       
   363 <pre class="programlisting">&gt;&gt;&gt; cplx = 3 + 4j #cplx is a complex variable
       
   364 &gt;&gt;&gt; cplx
       
   365 (3+4j)
       
   366 &gt;&gt;&gt; print cplx.real #prints the real part of the complex number
       
   367 3.0
       
   368 &gt;&gt;&gt; print cplx.imag #prints the imaginary part of the complex number
       
   369 4.0
       
   370 &gt;&gt;&gt; print cplx*fl  #multiplies the real and imag parts of the complex number with the multiplier
       
   371 (9.42477+12.56636j)
       
   372 &gt;&gt;&gt; abs(cplx) #returns the absolute value of the complex number
       
   373 5.0
       
   374 
       
   375 </pre>
       
   376 <p id="x_74"></a>Python provides a datatype for complex numbers. Complex numbers are initialized as shown in the example above. The 
       
   377         <span class="emphasis"><em>real</em></span> and 
       
   378         <span class="emphasis"><em>imag</em></span> operators return the real and imaginary parts of the complex number as shown. The 
       
   379         <span class="emphasis"><em>abs()</em></span> returns the absolute value of the complex number.
       
   380       </p>
       
   381 </div>
       
   382 <div class="section" title="4.2. Variables">
       
   383 <div class="titlepage"><div><div><h3 class="title">
       
   384 <a name="variables"></a>4.2. Variables</h3></div></div></div>
       
   385 <p id="x_75"></a>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:</p>
       
   386 <div class="blockquote"><blockquote class="blockquote"><div class="itemizedlist"><ul class="itemizedlist" type="*">
       
   387 <li class="listitem" style="list-style-type: *"><p id="x_76"></a>Variables have to be initialized or assigned a value before being used.</p></li>
       
   388 <li class="listitem" style="list-style-type: *"><p id="x_77"></a>Variable names can consist of letters, digits and 
       
   389               <a class="link" href="">underscores</a> .
       
   390             </p></li>
       
   391 <li class="listitem" style="list-style-type: *"><p id="x_78"></a>Variable names cannot begin with digits, but can contain digits in them.</p></li>
       
   392 </ul></div></blockquote></div>
       
   393 <p id="x_79"></a>In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' are all variables of various datatypes.</p>
       
   394 <pre class="programlisting">Note: Python is not a strongly typed language and hence an integer variable can at a
       
   395 later stage be used as a float variable as well.
       
   396 
       
   397 </pre>
       
   398 </div>
       
   399 <div class="section" title="4.3. Strings">
       
   400 <div class="titlepage"><div><div><h3 class="title">
       
   401 <a name="strings"></a>4.3. Strings</h3></div></div></div>
       
   402 <p id="x_7a"></a>Strings are one of the essential data structures of any programming language. The 
       
   403         <code class="literal">print "Hello, World!"</code> program was introduced in the earlier section, and the 
       
   404         <span class="emphasis"><em>"Hello, World!"</em></span> in the print statement is a string. A string is basically a set of characters. Strings can be represented in various ways shown below:
       
   405       </p>
       
   406 <pre class="programlisting">s = 'this is a string'              # a string variable can be represented using single quotes
       
   407 s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
       
   408 s = "I have 'single-quotes' inside!"
       
   409 l = "A string spanning many lines\
       
   410 one more line\
       
   411 yet another"                        # a string can span more than a single line.
       
   412 t = """A triple quoted string does  # another way of representing multiline strings.
       
   413 not need to be escaped at the end and
       
   414 "can have nested quotes" etc."""
       
   415 
       
   416 </pre>
       
   417 <p id="x_7b"></a>Try the following on the interpreter: 
       
   418         <code class="literal">s = 'this is a string with 'quotes' of similar kind'</code>
       
   419       </p>
       
   420 <p id="x_7c"></a>
       
   421         <span class="strong"><strong>Exercise: How to use single quotes within single quotes in a string as shown in the above example without getting an error?</strong></span>
       
   422       </p>
       
   423 <div class="section" title="4.3.1. String operations">
       
   424 <div class="titlepage"><div><div><h4 class="title">
       
   425 <a name="string-operations"></a>4.3.1. String operations</h4></div></div></div>
       
   426 <p id="x_7d"></a>A few basic string operations are presented here.</p>
       
   427 <p id="x_7e"></a>
       
   428           <span class="strong"><strong>String concatenation</strong></span> String concatenation is done by simple addition of two strings.
       
   429         </p>
       
   430 <pre class="programlisting">&gt;&gt;&gt; x = 'Hello'
       
   431 &gt;&gt;&gt; y = ' Python'
       
   432 &gt;&gt;&gt; print x+y
       
   433 Hello Python
       
   434 
       
   435 </pre>
       
   436 <p id="x_7f"></a>          <span class="emphasis"><em>Try this yourself:</em></span>
       
   437         </p>
       
   438 <pre class="programlisting">&gt;&gt;&gt; somenum = 13
       
   439 &gt;&gt;&gt; print x+somenum
       
   440 
       
   441 </pre>
       
   442 <p id="x_80"></a>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.</p>
       
   443 <p id="x_81"></a>
       
   444           <span class="strong"><strong>str()</strong></span> simply converts a value to a string in a reasonable form. 
       
   445           <span class="strong"><strong>repr()</strong></span> creates a string that is a representation of the value.
       
   446         </p>
       
   447 <p id="x_82"></a>The difference can be seen in the example shown below:</p>
       
   448 <pre class="programlisting">&gt;&gt;&gt; str(1000000000000000000000000000000000000000000000000L)
       
   449 '1000000000000000000000000000000000000000000000000'
       
   450 &gt;&gt;&gt; repr(1000000000000000000000000000000000000000000000000L)
       
   451 '1000000000000000000000000000000000000000000000000L'
       
   452 
       
   453 </pre>
       
   454 <p id="x_83"></a>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 `
       
   455           <code class="literal">value</code>`.
       
   456         </p>
       
   457 <p id="x_84"></a>A few more examples:</p>
       
   458 <pre class="programlisting">&gt;&gt;&gt; x = "Let's go \nto Pycon"
       
   459 &gt;&gt;&gt; print x
       
   460 Let's go 
       
   461 to Pycon
       
   462 
       
   463 </pre>
       
   464 <p id="x_85"></a>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.</p>
       
   465 <p id="x_86"></a>
       
   466           <span class="strong"><strong>Raw strings</strong></span> 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
       
   467         </p>
       
   468 <pre class="programlisting">&gt;&gt;&gt; x = r"Let's go \nto Pycon"
       
   469 &gt;&gt;&gt; print x
       
   470 Let's go \nto Pycon
       
   471 
       
   472 </pre>
       
   473 <p id="x_87"></a>Note: The '\n' is not being parsed into a new line and is left as it is.</p>
       
   474 <p id="x_88"></a>
       
   475           <span class="emphasis"><em>Try this yourself:</em></span>
       
   476         </p>
       
   477 <pre class="programlisting">&gt;&gt;&gt; x = r"Let's go to Pycon\"
       
   478 
       
   479 </pre>
       
   480 <p id="x_89"></a>          <span class="strong"><strong>Unicode strings</strong></span> 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:
       
   481         </p>
       
   482 <pre class="programlisting">&gt;&gt;&gt; x = u"Let's go to Pycon!"
       
   483 &gt;&gt;&gt; print x
       
   484 Let's go to Pycon!
       
   485 
       
   486 </pre>
       
   487 </div>
       
   488 </div>
       
   489 <div class="section" title="4.4. Boolean">
       
   490 <div class="titlepage"><div><div><h3 class="title">
       
   491 <a name="boolean"></a>4.4. Boolean</h3></div></div></div>
       
   492 <p id="x_8a"></a>Python also provides special Boolean datatype. A boolean variable can assume a value of either 
       
   493         <span class="emphasis"><em>True</em></span> or 
       
   494         <span class="emphasis"><em>False</em></span> (Note the capitalizations).
       
   495       </p>
       
   496 <p id="x_8b"></a>Let us look at examples:</p>
       
   497 <pre class="programlisting">&gt;&gt;&gt; t = True
       
   498 &gt;&gt;&gt; f = not t
       
   499 &gt;&gt;&gt; print f
       
   500 False
       
   501 &gt;&gt;&gt; f or t
       
   502 True
       
   503 &gt;&gt;&gt; f and t
       
   504 False
       
   505 
       
   506 </pre>
       
   507 </div>
       
   508 </div>
       
   509 <div class="section" title="5. The while loop">
       
   510 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   511 <a name="the-while-loop"></a>5. The 
       
   512       <span class="strong"><strong>while</strong></span> loop
       
   513     </h2></div></div></div>
       
   514 <p id="x_8c"></a>The Python 
       
   515       <span class="strong"><strong>while</strong></span> loop is similar to the C/C++ while loop. The syntax is as follows:
       
   516     </p>
       
   517 <pre class="programlisting">statement 0
       
   518 while condition:
       
   519   statement 1 #while block
       
   520   statement 2 #while block
       
   521 statement 3 #outside the while block.
       
   522 
       
   523 </pre>
       
   524 <p id="x_8d"></a>Let us look at an example:</p>
       
   525 <pre class="programlisting">&gt;&gt;&gt; x = 1  
       
   526 &gt;&gt;&gt; while x &lt;= 5:
       
   527 ...   print x
       
   528 ...   x += 1
       
   529 ... 
       
   530 1
       
   531 2
       
   532 3
       
   533 4
       
   534 5
       
   535 
       
   536 </pre>
       
   537 </div>
       
   538 <div class="section" title="6. The if conditional">
       
   539 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   540 <a name="the-if-conditional"></a>6. The 
       
   541       <span class="strong"><strong>if</strong></span> conditional
       
   542     </h2></div></div></div>
       
   543 <p id="x_8e"></a>The Python 
       
   544       <span class="strong"><strong>if</strong></span> block provides the conditional execution of statements. If the condition evaluates as true the block of statements defined under the if block are executed.
       
   545     </p>
       
   546 <p id="x_8f"></a>If the first block is not executed on account of the condition not being satisfied, the set of statements in the 
       
   547       <span class="strong"><strong>else</strong></span> block are executed.
       
   548     </p>
       
   549 <p id="x_90"></a>The 
       
   550       <span class="strong"><strong>elif</strong></span> block provides the functionality of evaluation of multiple conditions as shown in the example.
       
   551     </p>
       
   552 <p id="x_91"></a>The syntax is as follows:</p>
       
   553 <pre class="programlisting">if condition :
       
   554     statement_1
       
   555     statement_2
       
   556 
       
   557 elif condition:
       
   558     statement_3
       
   559     statement_4
       
   560 else:
       
   561     statement_5
       
   562     statement_6
       
   563 
       
   564 </pre>
       
   565 <p id="x_92"></a>Let us look at an example:</p>
       
   566 <pre class="programlisting">&gt;&gt;&gt; n = raw_input("Input a number:")
       
   567 &gt;&gt;&gt; if n &lt; 0:
       
   568       print n," is negative"
       
   569       elif n &gt; 0:
       
   570       print n," is positive"
       
   571       else:
       
   572       print n, " is 0"
       
   573 
       
   574 </pre>
       
   575 </div>
       
   576 <div class="section" title="7.  raw_input()">
       
   577 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   578 <a name="raw_input"></a>7.       <span class="strong"><strong>raw_input()</strong></span>
       
   579     </h2></div></div></div>
       
   580 <p id="x_93"></a>In the previous example we saw the call to the raw_input() subroutine. The 
       
   581       <span class="strong"><strong>raw_input()</strong></span> method is used to take user inputs through the console. Unlike 
       
   582       <span class="strong"><strong>input()</strong></span> which assumes the data entered by the user as a standard python expression, 
       
   583       <span class="strong"><strong>raw_input()</strong></span> treats all the input data as raw data and converts everything into a string. To illustrate this let us look at an example.
       
   584     </p>
       
   585 <pre class="programlisting">&gt;&gt;&gt; input("Enter a number thats a palindrome:")
       
   586 Enter a number thats a palindrome:121
       
   587 121
       
   588 
       
   589 &gt;&gt;&gt; input("Enter your name:")
       
   590 Enter your name:PythonFreak
       
   591 Traceback (most recent call last):
       
   592   File "&lt;stdin&gt;", line 1, in &lt;module&gt;
       
   593   File "&lt;string&gt;", line 1, in &lt;module&gt;
       
   594 NameError: name 'PythonFreak' is not defined
       
   595 
       
   596 </pre>
       
   597 <p id="x_94"></a>As shown above the 
       
   598       <span class="strong"><strong>input()</strong></span> 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, 
       
   599       <span class="strong"><strong>input()</strong></span> assumes that the entered data is a valid Python expression and hence it raises and exception saying PythonFreak is not defined.
       
   600     </p>
       
   601 <pre class="programlisting">&gt;&gt;&gt; input("Enter your name:")
       
   602 Enter your name:'PythonFreak'
       
   603 'PythonFreak'
       
   604 &gt;&gt;&gt; 
       
   605 
       
   606 </pre>
       
   607 <p id="x_95"></a>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 
       
   608       <span class="strong"><strong>raw_input()</strong></span>.
       
   609     </p>
       
   610 <p id="x_96"></a>Let us now look at how 
       
   611       <span class="strong"><strong>raw_input()</strong></span> operates with an example.
       
   612     </p>
       
   613 <pre class="programlisting">&gt;&gt;&gt; raw_input("Enter your name:")
       
   614 Enter your name:PythonFreak
       
   615 'PythonFreak'
       
   616 
       
   617 </pre>
       
   618 <p id="x_97"></a>Observe that the 
       
   619       <span class="strong"><strong>raw_input()</strong></span> is converting it into a string all by itself.
       
   620     </p>
       
   621 <pre class="programlisting">&gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
       
   622 Enter a number thats a palindrome:121
       
   623 '121'
       
   624 
       
   625 </pre>
       
   626 <p id="x_98"></a>Observe that 
       
   627       <span class="strong"><strong>raw_input()</strong></span> is converting the integer 121 also to a string as '121'. Let us look at another example:
       
   628     </p>
       
   629 <pre class="programlisting">&gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
       
   630 Enter a number thats a palindrome:121
       
   631 &gt;&gt;&gt; pal + 2
       
   632 Traceback (most recent call last):
       
   633   File "&lt;stdin&gt;", line 1, in &lt;module&gt;
       
   634 TypeError: cannot concatenate 'str' and 'int' objects
       
   635 &gt;&gt;&gt; pal
       
   636 '121'
       
   637 
       
   638 </pre>
       
   639 <p id="x_99"></a>Observe here that the variable 
       
   640       <span class="emphasis"><em>pal</em></span> is a string and hence integer operations cannot be performed on it. Hence the exception is raised.
       
   641     </p>
       
   642 </div>
       
   643 <div class="section" title="8.  int() method">
       
   644 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   645 <a name="int-method"></a>8. 
       
   646       <span class="strong"><strong>int()</strong></span> method
       
   647     </h2></div></div></div>
       
   648 <p id="x_9a"></a>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 
       
   649       <span class="strong"><strong>raw_input()</strong></span> is raw data in the form of strings. In order to obtain integers from strings we use the method 
       
   650       <span class="strong"><strong>int()</strong></span>.
       
   651     </p>
       
   652 <p id="x_9b"></a>Let us look at an example.</p>
       
   653 <pre class="programlisting">&gt;&gt;&gt; intpal = int(pal)
       
   654 &gt;&gt;&gt; intpal
       
   655 121
       
   656 
       
   657 </pre>
       
   658 <p id="x_9c"></a>In the previous example it was observed that 
       
   659       <span class="emphasis"><em>pal</em></span> was a string variable. Here using the 
       
   660       <span class="strong"><strong>int()</strong></span> method the string 
       
   661       <span class="emphasis"><em>pal</em></span> was converted to an integer variable.
       
   662     </p>
       
   663 <p id="x_9d"></a>
       
   664       <span class="emphasis"><em>Try This Yourself:</em></span>
       
   665     </p>
       
   666 <pre class="programlisting">&gt;&gt;&gt; stringvar = raw_input("Enter a name:")
       
   667 Enter a name:Guido Van Rossum
       
   668 &gt;&gt;&gt; stringvar
       
   669 'Guido Van Rossum'
       
   670 &gt;&gt;&gt; numvar = int(stringvar)
       
   671 
       
   672 </pre>
       
   673 </div>
       
   674 </div>
       
   675 <div class="navfooter">
       
   676 <hr>
       
   677 <table width="100%" summary="Navigation footer">
       
   678 <tr>
       
   679 <td width="40%" align="left">
       
   680 <a accesskey="p" href="index.html">Prev</a> </td>
       
   681 <td width="20%" align="center"> </td>
       
   682 <td width="40%" align="right"> </td>
       
   683 </tr>
       
   684 <tr>
       
   685 <td width="40%" align="left" valign="top">Chapter 1. Introduction </td>
       
   686 <td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td>
       
   687 <td width="40%" align="right" valign="top"> </td>
       
   688 </tr>
       
   689 </table>
       
   690 </div>
       
   691 </body>
       
   692 </html>