web/html/ch02-basic_intro.html~
changeset 1 672eaaab9204
parent 0 8083d21c0020
child 2 52d12eb31c30
equal deleted inserted replaced
0:8083d21c0020 1:672eaaab9204
     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="chapter" lang="en" id="chap02_basic">
       
    14 <div class="article" title="Basic Python">
       
    15 <div class="titlepage">
       
    16 <div><div><h2 class="title">
       
    17 <a name="id2957059"></a>Basic Python</h2></div></div>
       
    18 <hr>
       
    19 </div>
       
    20 <div class="toc">
       
    21 <p><b>Table of Contents</b></p>
       
    22 <dl>
       
    23 <dt><span class="section"><a href="#introduction">1. Introduction</a></span></dt>
       
    24 <dt><span class="section"><a href="#the-python-interpreter">2. The Python Interpreter</a></span></dt>
       
    25 <dd><dl>
       
    26 <dt><span class="section"><a href="#the-interactive-interpreter">2.1. The Interactive Interpreter</a></span></dt>
       
    27 <dt><span class="section"><a href="#ipython-an-enhanced-interactive-python-interpreter">2.2. 
       
    28         <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter
       
    29       </a></span></dt>
       
    30 </dl></dd>
       
    31 <dt><span class="section"><a href="#editing-and-running-a-python-file">3. Editing and running a python file</a></span></dt>
       
    32 <dt><span class="section"><a href="#basic-datatypes-and-operators-in-python">4. Basic Datatypes and operators in Python</a></span></dt>
       
    33 <dd><dl>
       
    34 <dt><span class="section"><a href="#numbers">4.1. Numbers</a></span></dt>
       
    35 <dt><span class="section"><a href="#variables">4.2. Variables</a></span></dt>
       
    36 <dt><span class="section"><a href="#strings">4.3. Strings</a></span></dt>
       
    37 <dt><span class="section"><a href="#boolean">4.4. Boolean</a></span></dt>
       
    38 </dl></dd>
       
    39 <dt><span class="section"><a href="#the-while-loop">5. The 
       
    40       <span class="strong"><strong>while</strong></span> loop
       
    41     </a></span></dt>
       
    42 <dt><span class="section"><a href="#the-if-conditional">6. The 
       
    43       <span class="strong"><strong>if</strong></span> conditional
       
    44     </a></span></dt>
       
    45 <dt><span class="section"><a href="#raw_input">7.       <span class="strong"><strong>raw_input()</strong></span>
       
    46     </a></span></dt>
       
    47 <dt><span class="section"><a href="#int-method">8. 
       
    48       <span class="strong"><strong>int()</strong></span> method
       
    49     </a></span></dt>
       
    50 </dl>
       
    51 </div>
       
    52 <p id="x_197"></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>
       
    53 <p id="x_198"></a>The system requirements:</p>
       
    54 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
    55 <li class="listitem" style="list-style-type: *"><p id="x_199"></a>Python - version 2.5.x or newer.</p></li>
       
    56 <li class="listitem" style="list-style-type: *"><p id="x_19a"></a>IPython</p></li>
       
    57 <li class="listitem" style="list-style-type: *"><p id="x_19b"></a>Text editor - scite, vim, emacs or whatever you are comfortable with.</p></li>
       
    58 </ul></div>
       
    59 <div class="section" title="1. Introduction">
       
    60 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
    61 <a name="introduction"></a>1. Introduction</h2></div></div></div>
       
    62 <p id="x_19c"></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>
       
    63 <p id="x_19d"></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>
       
    64 <p id="x_19e"></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>
       
    65 <p id="x_19f"></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 
       
    66       <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.
       
    67     </p>
       
    68 <p id="x_1a0"></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>
       
    69 <p id="x_1a1"></a>
       
    70       <span class="strong"><strong>Resources available for reference</strong></span>
       
    71     </p>
       
    72 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
    73 <li class="listitem" style="list-style-type: *"><p id="x_1a2"></a>Web: 
       
    74           <a class="ulink" href="http://www.python.org" target="_top">http://www.python.org</a>
       
    75         </p></li>
       
    76 <li class="listitem" style="list-style-type: *"><p id="x_1a3"></a>Doc: 
       
    77           <a class="ulink" href="http://www.python.org/doc" target="_top">http://www.python.org/doc</a>
       
    78         </p></li>
       
    79 <li class="listitem" style="list-style-type: *"><p id="x_1a4"></a>Free Tutorials: 
       
    80           <span class="emphasis"><em> Official Python Tutorial: 
       
    81             <a class="ulink" href="http://docs.python.org/tut/tut.html" target="_top">http://docs.python.org/tut/tut.html</a> 
       
    82           </em></span> Byte of Python: 
       
    83           <a class="ulink" href="http://www.byteofpython.info" target="_top">http://www.byteofpython.info</a>/ * Dive into Python: 
       
    84           <a class="ulink" href="http://diveintopython.org" target="_top">http://diveintopython.org</a>/
       
    85         </p></li>
       
    86 </ul></div>
       
    87 <p id="x_1a5"></a>
       
    88       <span class="strong"><strong>Advantages of Python - Why Python??</strong></span>
       
    89     </p>
       
    90 <div class="itemizedlist"><ul class="itemizedlist" type="*">
       
    91 <li class="listitem" style="list-style-type: *"><p id="x_1a6"></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>
       
    92 <li class="listitem" style="list-style-type: *"><p id="x_1a7"></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>
       
    93 <li class="listitem" style="list-style-type: *"><p id="x_1a8"></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>
       
    94 <li class="listitem" style="list-style-type: *"><p id="x_1a9"></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 
       
    95           <a class="ulink" href="http://xkcd.com/353" target="_top">http://xkcd.com/353</a>/
       
    96         </p></li>
       
    97 <li class="listitem" style="list-style-type: *"><p id="x_1aa"></a>Python interfaces well with most other programming languages such as C, C++  and FORTRAN.</p></li>
       
    98 </ul></div>
       
    99 <p id="x_1ab"></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>
       
   100 </div>
       
   101 <div class="section" title="2. The Python Interpreter">
       
   102 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   103 <a name="the-python-interpreter"></a>2. The Python Interpreter</h2></div></div></div>
       
   104 <div class="section" title="2.1. The Interactive Interpreter">
       
   105 <div class="titlepage"><div><div><h3 class="title">
       
   106 <a name="the-interactive-interpreter"></a>2.1. The Interactive Interpreter</h3></div></div></div>
       
   107 <p id="x_1ac"></a>Typing 
       
   108         <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 
       
   109         <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.
       
   110       </p>
       
   111 <pre class="programlisting">Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
       
   112 [GCC 4.3.2] on linux2
       
   113 Type "help", "copyright", "credits" or "license" for more information.
       
   114 &gt;&gt;&gt; 
       
   115 
       
   116 </pre>
       
   117 <p id="x_1ad"></a>Lets try with an example, type 
       
   118         <code class="literal">print 'Hello, World!'</code> at the prompt and hit the enter key.
       
   119       </p>
       
   120 <pre class="programlisting">&gt;&gt;&gt; print 'Hello, World!'
       
   121 Hello, World!
       
   122 
       
   123 </pre>
       
   124 <p id="x_1ae"></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>
       
   125 <pre class="programlisting">&gt;&gt;&gt; arbit word
       
   126   File "&lt;stdin&gt;", line 1
       
   127     arbit word
       
   128             ^
       
   129 SyntaxError: invalid syntax
       
   130 &gt;&gt;&gt;
       
   131 
       
   132 </pre>
       
   133 <p id="x_1af"></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 
       
   134         <span class="emphasis"><em>help()</em></span> at the prompt gives the following output:
       
   135       </p>
       
   136 <pre class="programlisting">&gt;&gt;&gt; help()
       
   137 
       
   138 Welcome to Python 2.5!  This is the online help utility.
       
   139 
       
   140 If this is your first time using Python, you should definitely check out
       
   141 the tutorial on the Internet at http://www.python.org/doc/tut/.
       
   142 
       
   143 Enter the name of any module, keyword, or topic to get help on writing
       
   144 Python programs and using Python modules.  To quit this help utility and
       
   145 return to the interpreter, just type "quit".
       
   146 
       
   147 To get a list of available modules, keywords, or topics, type "modules",
       
   148 "keywords", or "topics".  Each module also comes with a one-line summary
       
   149 of what it does; to list the modules whose summaries contain a given word
       
   150 such as "spam", type "modules spam".
       
   151 
       
   152 help&gt; 
       
   153 
       
   154 
       
   155 </pre>
       
   156 <p id="x_1b0"></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 
       
   157         <span class="emphasis"><em>Ctrl+d</em></span> exits the help prompt and returns to the python prompt.
       
   158       </p>
       
   159 <p id="x_1b1"></a>Let us now try a few examples at the python interpreter.</p>
       
   160 <p id="x_1b2"></a>Eg 1:</p>
       
   161 <pre class="programlisting">&gt;&gt;&gt; print 'Hello, python!'
       
   162 Hello, python!
       
   163 &gt;&gt;&gt;
       
   164 
       
   165 </pre>
       
   166 <p id="x_1b3"></a>Eg 2:</p>
       
   167 <pre class="programlisting">&gt;&gt;&gt; print 4321*567890
       
   168 2453852690
       
   169 &gt;&gt;&gt; 
       
   170 
       
   171 </pre>
       
   172 <p id="x_1b4"></a>Eg 3:</p>
       
   173 <pre class="programlisting">&gt;&gt;&gt; 4321*567890
       
   174 2453852690L
       
   175 &gt;&gt;&gt;
       
   176 
       
   177 </pre>
       
   178 <pre class="programlisting">Note: Notice the 'L' at the end of the output. The 'L' signifies that the
       
   179 output of the operation is of type *long*. It was absent in the previous
       
   180 example because we used the print statement. This is because *print* formats
       
   181 the output before displaying.
       
   182 
       
   183 </pre>
       
   184 <p id="x_1b5"></a>Eg 4:</p>
       
   185 <pre class="programlisting">&gt;&gt;&gt; big = 12345678901234567890 ** 3
       
   186 &gt;&gt;&gt; print big
       
   187 1881676372353657772490265749424677022198701224860897069000
       
   188 &gt;&gt;&gt; 
       
   189 
       
   190 </pre>
       
   191 <pre class="programlisting">This example is to show that unlike in C or C++ there is no limit on the
       
   192 value of an integer.
       
   193 
       
   194 </pre>
       
   195 <p id="x_1b6"></a>Try this on the interactive interpreter: 
       
   196         <code class="literal">import this</code>
       
   197       </p>
       
   198 <p id="x_1b7"></a>
       
   199         <span class="emphasis"><em>Hint: The output gives an idea of Power of Python</em></span>
       
   200       </p>
       
   201 </div>
       
   202 <div class="section" title="2.2.  ipython - An enhanced interactive Python interpreter">
       
   203 <div class="titlepage"><div><div><h3 class="title">
       
   204 <a name="ipython-an-enhanced-interactive-python-interpreter"></a>2.2. 
       
   205         <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter
       
   206       </h3></div></div></div>
       
   207 <p id="x_1b8"></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 
       
   208         <span class="strong"><strong>ipython</strong></span>. Entering 
       
   209         <span class="emphasis"><em>ipython</em></span> at the shell prompt fires up the interactive interpreter.
       
   210       </p>
       
   211 <pre class="programlisting">$ ipython
       
   212 Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
       
   213 Type "copyright", "credits" or "license" for more information.
       
   214 
       
   215 IPython 0.8.4 -- An enhanced Interactive Python.
       
   216 ?         -&gt; Introduction and overview of IPython's features.
       
   217 %quickref -&gt; Quick reference.
       
   218 help      -&gt; Python's own help system.
       
   219 object?   -&gt; Details about 'object'. ?object also works, ?? prints more.
       
   220 
       
   221 In [1]: 
       
   222 
       
   223 </pre>
       
   224 <p id="x_1b9"></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 
       
   225         <span class="strong"><strong>ipython</strong></span>:
       
   226       </p>
       
   227 <div class="variablelist"><dl>
       
   228 <dt><span class="term"></span></dt>
       
   229 <dd>
       
   230 <p></p>
       
   231 <p id="x_1ba"></a>Suggestions - ipython provides suggestions of the possible methods and operations available for the given python object.</p>
       
   232 </dd>
       
   233 </dl></div>
       
   234 <p id="x_1bb"></a>Eg 5:</p>
       
   235 <pre class="programlisting">In [4]: a = 6
       
   236 
       
   237 In [5]: a.
       
   238 a.__abs__           a.__divmod__        a.__index__         a.__neg__          a.__rand__          a.__rmod__          a.__rxor__
       
   239 a.__add__           a.__doc__           a.__init__          a.__new__          a.__rdiv__          a.__rmul__          a.__setattr__
       
   240 a.__and__           a.__float__         a.__int__           a.__nonzero__      a.__rdivmod__       a.__ror__           a.__str__
       
   241 a.__class__         a.__floordiv__      a.__invert__        a.__oct__          a.__reduce__        a.__rpow__          a.__sub__
       
   242 a.__cmp__           a.__getattribute__  a.__long__          a.__or__           a.__reduce_ex__     a.__rrshift__       a.__truediv__
       
   243 a.__coerce__        a.__getnewargs__    a.__lshift__        a.__pos__          a.__repr__          a.__rshift__        a.__xor__
       
   244 a.__delattr__       a.__hash__          a.__mod__           a.__pow__          a.__rfloordiv__     a.__rsub__          
       
   245 a.__div__           a.__hex__           a.__mul__           a.__radd__         a.__rlshift__       a.__rtruediv__      
       
   246 
       
   247 </pre>
       
   248 <p id="x_1bc"></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 
       
   249         <span class="emphasis"><em>tab</em></span> key is pressed after typing '
       
   250         <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.
       
   251       </p>
       
   252 </div>
       
   253 </div>
       
   254 <div class="section" title="3. Editing and running a python file">
       
   255 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   256 <a name="editing-and-running-a-python-file"></a>3. Editing and running a python file</h2></div></div></div>
       
   257 <p id="x_1bd"></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 
       
   258       <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.
       
   259     </p>
       
   260 <p id="x_1be"></a>Let us look at a simple example of calculating the gcd of 2 numbers using Python:</p>
       
   261 <p id="x_1bf"></a>
       
   262       <span class="strong"><strong>Creating the first python script(file)</strong></span> :
       
   263     </p>
       
   264 <pre class="programlisting">$ emacs gcd.py
       
   265   def gcd(x,y):
       
   266     if x % y == 0:
       
   267       return y
       
   268     return gcd(y, x%y)
       
   269 
       
   270   print gcd(72, 92)
       
   271 
       
   272 </pre>
       
   273 <p id="x_1c0"></a>To run the script, open the shell prompt, navigate to the directory that contains the python file and run 
       
   274       <code class="literal">python &lt;filename.py&gt;</code> at the prompt ( in this case filename is gcd.py )
       
   275     </p>
       
   276 <p id="x_1c1"></a>
       
   277       <span class="strong"><strong>Running the python script</strong></span> :
       
   278     </p>
       
   279 <pre class="programlisting">$ python gcd.py
       
   280 4
       
   281 $ 
       
   282 
       
   283 </pre>
       
   284 <p id="x_1c2"></a>Another method to run a python script would be to include the line</p>
       
   285 <p id="x_1c3"></a>
       
   286       <code class="literal">#! /usr/bin/python</code>
       
   287     </p>
       
   288 <p id="x_1c4"></a>at the beginning of the python file and then make the file executable by</p>
       
   289 <p id="x_1c5"></a>$ chmod a+x 
       
   290       <span class="emphasis"><em>filename.py</em></span>
       
   291     </p>
       
   292 <p id="x_1c6"></a>Once this is done, the script can be run as a standalone program as follows:</p>
       
   293 <p id="x_1c7"></a>$ ./
       
   294       <span class="emphasis"><em>filename.py</em></span>
       
   295     </p>
       
   296 </div>
       
   297 <div class="section" title="4. Basic Datatypes and operators in Python">
       
   298 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   299 <a name="basic-datatypes-and-operators-in-python"></a>4. Basic Datatypes and operators in Python</h2></div></div></div>
       
   300 <p id="x_1c8"></a>Python provides the following set of basic datatypes.</p>
       
   301 <div class="blockquote"><blockquote class="blockquote"><div class="itemizedlist"><ul class="itemizedlist" type="*">
       
   302 <li class="listitem" style="list-style-type: *"><p id="x_1c9"></a>Numbers: int, float, long, complex</p></li>
       
   303 <li class="listitem" style="list-style-type: *"><p id="x_1ca"></a>Strings</p></li>
       
   304 <li class="listitem" style="list-style-type: *"><p id="x_1cb"></a>Boolean</p></li>
       
   305 </ul></div></blockquote></div>
       
   306 <div class="section" title="4.1. Numbers">
       
   307 <div class="titlepage"><div><div><h3 class="title">
       
   308 <a name="numbers"></a>4.1. Numbers</h3></div></div></div>
       
   309 <p id="x_1cc"></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>
       
   310 <p id="x_1cd"></a>Eg 6:</p>
       
   311 <pre class="programlisting">&gt;&gt;&gt; a = 1 #here a is an integer variable
       
   312 
       
   313 </pre>
       
   314 <p id="x_1ce"></a>Eg 7:</p>
       
   315 <pre class="programlisting">&gt;&gt;&gt; lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long
       
   316 &gt;&gt;&gt; lng
       
   317 122333444455555666666777777788888888999999999L #notice the trailing 'L'
       
   318 &gt;&gt;&gt; print lng
       
   319 122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'
       
   320 &gt;&gt;&gt; lng+1
       
   321 122333444455555666666777777788888889000000000L
       
   322 
       
   323 
       
   324 </pre>
       
   325 <p id="x_1cf"></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 
       
   326         <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.
       
   327       </p>
       
   328 <p id="x_1d0"></a>Eg 8:</p>
       
   329 <pre class="programlisting">&gt;&gt;&gt; fl = 3.14159 #fl is a float variable
       
   330 &gt;&gt;&gt; e = 1.234e-4 #e is also a float variable, specified in the exponential form
       
   331 &gt;&gt;&gt; a = 1
       
   332 &gt;&gt;&gt; b = 2
       
   333 &gt;&gt;&gt; a/b #integer division
       
   334 0
       
   335 &gt;&gt;&gt; a/fl #floating point division
       
   336 0.31831015504887655
       
   337 &gt;&gt;&gt; e/fl
       
   338 3.9279473133031364e-05
       
   339 
       
   340 
       
   341 </pre>
       
   342 <p id="x_1d1"></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>
       
   343 <p id="x_1d2"></a>Eg 9:</p>
       
   344 <pre class="programlisting">&gt;&gt;&gt; cplx = 3 + 4j #cplx is a complex variable
       
   345 &gt;&gt;&gt; cplx
       
   346 (3+4j)
       
   347 &gt;&gt;&gt; print cplx.real #prints the real part of the complex number
       
   348 3.0
       
   349 &gt;&gt;&gt; print cplx.imag #prints the imaginary part of the complex number
       
   350 4.0
       
   351 &gt;&gt;&gt; print cplx*fl  #multiplies the real and imag parts of the complex number with the multiplier
       
   352 (9.42477+12.56636j)
       
   353 &gt;&gt;&gt; abs(cplx) #returns the absolute value of the complex number
       
   354 5.0
       
   355 
       
   356 </pre>
       
   357 <p id="x_1d3"></a>Python provides a datatype for complex numbers. Complex numbers are initialized as shown in the example above. The 
       
   358         <span class="emphasis"><em>real</em></span> and 
       
   359         <span class="emphasis"><em>imag</em></span> operators return the real and imaginary parts of the complex number as shown. The 
       
   360         <span class="emphasis"><em>abs()</em></span> returns the absolute value of the complex number.
       
   361       </p>
       
   362 </div>
       
   363 <div class="section" title="4.2. Variables">
       
   364 <div class="titlepage"><div><div><h3 class="title">
       
   365 <a name="variables"></a>4.2. Variables</h3></div></div></div>
       
   366 <p id="x_1d4"></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>
       
   367 <div class="blockquote"><blockquote class="blockquote"><div class="itemizedlist"><ul class="itemizedlist" type="*">
       
   368 <li class="listitem" style="list-style-type: *"><p id="x_1d5"></a>Variables have to be initialized or assigned a value before being used.</p></li>
       
   369 <li class="listitem" style="list-style-type: *"><p id="x_1d6"></a>Variable names can consist of letters, digits and 
       
   370               <a class="link" href="#">underscores</a> .
       
   371             </p></li>
       
   372 <li class="listitem" style="list-style-type: *"><p id="x_1d7"></a>Variable names cannot begin with digits, but can contain digits in them.</p></li>
       
   373 </ul></div></blockquote></div>
       
   374 <p id="x_1d8"></a>In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' are all variables of various datatypes.</p>
       
   375 <pre class="programlisting">Note: Python is not a strongly typed language and hence an integer variable can at a
       
   376 later stage be used as a float variable as well.
       
   377 
       
   378 </pre>
       
   379 </div>
       
   380 <div class="section" title="4.3. Strings">
       
   381 <div class="titlepage"><div><div><h3 class="title">
       
   382 <a name="strings"></a>4.3. Strings</h3></div></div></div>
       
   383 <p id="x_1d9"></a>Strings are one of the essential data structures of any programming language. The 
       
   384         <code class="literal">print "Hello, World!"</code> program was introduced in the earlier section, and the 
       
   385         <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:
       
   386       </p>
       
   387 <pre class="programlisting">s = 'this is a string'              # a string variable can be represented using single quotes
       
   388 s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown
       
   389 s = "I have 'single-quotes' inside!"
       
   390 l = "A string spanning many lines\
       
   391 one more line\
       
   392 yet another"                        # a string can span more than a single line.
       
   393 t = """A triple quoted string does  # another way of representing multiline strings.
       
   394 not need to be escaped at the end and
       
   395 "can have nested quotes" etc."""
       
   396 
       
   397 </pre>
       
   398 <p id="x_1da"></a>Try the following on the interpreter: 
       
   399         <code class="literal">s = 'this is a string with 'quotes' of similar kind'</code>
       
   400       </p>
       
   401 <p id="x_1db"></a>
       
   402         <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>
       
   403       </p>
       
   404 <div class="section" title="4.3.1. String operations">
       
   405 <div class="titlepage"><div><div><h4 class="title">
       
   406 <a name="string-operations"></a>4.3.1. String operations</h4></div></div></div>
       
   407 <p id="x_1dc"></a>A few basic string operations are presented here.</p>
       
   408 <p id="x_1dd"></a>
       
   409           <span class="strong"><strong>String concatenation</strong></span> String concatenation is done by simple addition of two strings.
       
   410         </p>
       
   411 <pre class="programlisting">&gt;&gt;&gt; x = 'Hello'
       
   412 &gt;&gt;&gt; y = ' Python'
       
   413 &gt;&gt;&gt; print x+y
       
   414 Hello Python
       
   415 
       
   416 </pre>
       
   417 <p id="x_1de"></a>          <span class="emphasis"><em>Try this yourself:</em></span>
       
   418         </p>
       
   419 <pre class="programlisting">&gt;&gt;&gt; somenum = 13
       
   420 &gt;&gt;&gt; print x+somenum
       
   421 
       
   422 </pre>
       
   423 <p id="x_1df"></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>
       
   424 <p id="x_1e0"></a>
       
   425           <span class="strong"><strong>str()</strong></span> simply converts a value to a string in a reasonable form. 
       
   426           <span class="strong"><strong>repr()</strong></span> creates a string that is a representation of the value.
       
   427         </p>
       
   428 <p id="x_1e1"></a>The difference can be seen in the example shown below:</p>
       
   429 <pre class="programlisting">&gt;&gt;&gt; str(1000000000000000000000000000000000000000000000000L)
       
   430 '1000000000000000000000000000000000000000000000000'
       
   431 &gt;&gt;&gt; repr(1000000000000000000000000000000000000000000000000L)
       
   432 '1000000000000000000000000000000000000000000000000L'
       
   433 
       
   434 </pre>
       
   435 <p id="x_1e2"></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 `
       
   436           <code class="literal">value</code>`.
       
   437         </p>
       
   438 <p id="x_1e3"></a>A few more examples:</p>
       
   439 <pre class="programlisting">&gt;&gt;&gt; x = "Let's go \nto Pycon"
       
   440 &gt;&gt;&gt; print x
       
   441 Let's go 
       
   442 to Pycon
       
   443 
       
   444 </pre>
       
   445 <p id="x_1e4"></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>
       
   446 <p id="x_1e5"></a>
       
   447           <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
       
   448         </p>
       
   449 <pre class="programlisting">&gt;&gt;&gt; x = r"Let's go \nto Pycon"
       
   450 &gt;&gt;&gt; print x
       
   451 Let's go \nto Pycon
       
   452 
       
   453 </pre>
       
   454 <p id="x_1e6"></a>Note: The '\n' is not being parsed into a new line and is left as it is.</p>
       
   455 <p id="x_1e7"></a>
       
   456           <span class="emphasis"><em>Try this yourself:</em></span>
       
   457         </p>
       
   458 <pre class="programlisting">&gt;&gt;&gt; x = r"Let's go to Pycon\"
       
   459 
       
   460 </pre>
       
   461 <p id="x_1e8"></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:
       
   462         </p>
       
   463 <pre class="programlisting">&gt;&gt;&gt; x = u"Let's go to Pycon!"
       
   464 &gt;&gt;&gt; print x
       
   465 Let's go to Pycon!
       
   466 
       
   467 </pre>
       
   468 </div>
       
   469 </div>
       
   470 <div class="section" title="4.4. Boolean">
       
   471 <div class="titlepage"><div><div><h3 class="title">
       
   472 <a name="boolean"></a>4.4. Boolean</h3></div></div></div>
       
   473 <p id="x_1e9"></a>Python also provides special Boolean datatype. A boolean variable can assume a value of either 
       
   474         <span class="emphasis"><em>True</em></span> or 
       
   475         <span class="emphasis"><em>False</em></span> (Note the capitalizations).
       
   476       </p>
       
   477 <p id="x_1ea"></a>Let us look at examples:</p>
       
   478 <pre class="programlisting">&gt;&gt;&gt; t = True
       
   479 &gt;&gt;&gt; f = not t
       
   480 &gt;&gt;&gt; print f
       
   481 False
       
   482 &gt;&gt;&gt; f or t
       
   483 True
       
   484 &gt;&gt;&gt; f and t
       
   485 False
       
   486 
       
   487 </pre>
       
   488 </div>
       
   489 </div>
       
   490 <div class="section" title="5. The while loop">
       
   491 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   492 <a name="the-while-loop"></a>5. The 
       
   493       <span class="strong"><strong>while</strong></span> loop
       
   494     </h2></div></div></div>
       
   495 <p id="x_1eb"></a>The Python 
       
   496       <span class="strong"><strong>while</strong></span> loop is similar to the C/C++ while loop. The syntax is as follows:
       
   497     </p>
       
   498 <pre class="programlisting">statement 0
       
   499 while condition:
       
   500   statement 1 #while block
       
   501   statement 2 #while block
       
   502 statement 3 #outside the while block.
       
   503 
       
   504 </pre>
       
   505 <p id="x_1ec"></a>Let us look at an example:</p>
       
   506 <pre class="programlisting">&gt;&gt;&gt; x = 1  
       
   507 &gt;&gt;&gt; while x &lt;= 5:
       
   508 ...   print x
       
   509 ...   x += 1
       
   510 ... 
       
   511 1
       
   512 2
       
   513 3
       
   514 4
       
   515 5
       
   516 
       
   517 </pre>
       
   518 </div>
       
   519 <div class="section" title="6. The if conditional">
       
   520 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   521 <a name="the-if-conditional"></a>6. The 
       
   522       <span class="strong"><strong>if</strong></span> conditional
       
   523     </h2></div></div></div>
       
   524 <p id="x_1ed"></a>The Python 
       
   525       <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.
       
   526     </p>
       
   527 <p id="x_1ee"></a>If the first block is not executed on account of the condition not being satisfied, the set of statements in the 
       
   528       <span class="strong"><strong>else</strong></span> block are executed.
       
   529     </p>
       
   530 <p id="x_1ef"></a>The 
       
   531       <span class="strong"><strong>elif</strong></span> block provides the functionality of evaluation of multiple conditions as shown in the example.
       
   532     </p>
       
   533 <p id="x_1f0"></a>The syntax is as follows:</p>
       
   534 <pre class="programlisting">if condition :
       
   535     statement_1
       
   536     statement_2
       
   537 
       
   538 elif condition:
       
   539     statement_3
       
   540     statement_4
       
   541 else:
       
   542     statement_5
       
   543     statement_6
       
   544 
       
   545 </pre>
       
   546 <p id="x_1f1"></a>Let us look at an example:</p>
       
   547 <pre class="programlisting">&gt;&gt;&gt; n = raw_input("Input a number:")
       
   548 &gt;&gt;&gt; if n &lt; 0:
       
   549       print n," is negative"
       
   550       elif n &gt; 0:
       
   551       print n," is positive"
       
   552       else:
       
   553       print n, " is 0"
       
   554 
       
   555 </pre>
       
   556 </div>
       
   557 <div class="section" title="7.  raw_input()">
       
   558 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   559 <a name="raw_input"></a>7.       <span class="strong"><strong>raw_input()</strong></span>
       
   560     </h2></div></div></div>
       
   561 <p id="x_1f2"></a>In the previous example we saw the call to the raw_input() subroutine. The 
       
   562       <span class="strong"><strong>raw_input()</strong></span> method is used to take user inputs through the console. Unlike 
       
   563       <span class="strong"><strong>input()</strong></span> which assumes the data entered by the user as a standard python expression, 
       
   564       <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.
       
   565     </p>
       
   566 <pre class="programlisting">&gt;&gt;&gt; input("Enter a number thats a palindrome:")
       
   567 Enter a number thats a palindrome:121
       
   568 121
       
   569 
       
   570 &gt;&gt;&gt; input("Enter your name:")
       
   571 Enter your name:PythonFreak
       
   572 Traceback (most recent call last):
       
   573   File "&lt;stdin&gt;", line 1, in &lt;module&gt;
       
   574   File "&lt;string&gt;", line 1, in &lt;module&gt;
       
   575 NameError: name 'PythonFreak' is not defined
       
   576 
       
   577 </pre>
       
   578 <p id="x_1f3"></a>As shown above the 
       
   579       <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, 
       
   580       <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.
       
   581     </p>
       
   582 <pre class="programlisting">&gt;&gt;&gt; input("Enter your name:")
       
   583 Enter your name:'PythonFreak'
       
   584 'PythonFreak'
       
   585 &gt;&gt;&gt; 
       
   586 
       
   587 </pre>
       
   588 <p id="x_1f4"></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 
       
   589       <span class="strong"><strong>raw_input()</strong></span>.
       
   590     </p>
       
   591 <p id="x_1f5"></a>Let us now look at how 
       
   592       <span class="strong"><strong>raw_input()</strong></span> operates with an example.
       
   593     </p>
       
   594 <pre class="programlisting">&gt;&gt;&gt; raw_input("Enter your name:")
       
   595 Enter your name:PythonFreak
       
   596 'PythonFreak'
       
   597 
       
   598 </pre>
       
   599 <p id="x_1f6"></a>Observe that the 
       
   600       <span class="strong"><strong>raw_input()</strong></span> is converting it into a string all by itself.
       
   601     </p>
       
   602 <pre class="programlisting">&gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
       
   603 Enter a number thats a palindrome:121
       
   604 '121'
       
   605 
       
   606 </pre>
       
   607 <p id="x_1f7"></a>Observe that 
       
   608       <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:
       
   609     </p>
       
   610 <pre class="programlisting">&gt;&gt;&gt; pal = raw_input("Enter a number thats a palindrome:")
       
   611 Enter a number thats a palindrome:121
       
   612 &gt;&gt;&gt; pal + 2
       
   613 Traceback (most recent call last):
       
   614   File "&lt;stdin&gt;", line 1, in &lt;module&gt;
       
   615 TypeError: cannot concatenate 'str' and 'int' objects
       
   616 &gt;&gt;&gt; pal
       
   617 '121'
       
   618 
       
   619 </pre>
       
   620 <p id="x_1f8"></a>Observe here that the variable 
       
   621       <span class="emphasis"><em>pal</em></span> is a string and hence integer operations cannot be performed on it. Hence the exception is raised.
       
   622     </p>
       
   623 </div>
       
   624 <div class="section" title="8.  int() method">
       
   625 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   626 <a name="int-method"></a>8. 
       
   627       <span class="strong"><strong>int()</strong></span> method
       
   628     </h2></div></div></div>
       
   629 <p id="x_1f9"></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 
       
   630       <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 
       
   631       <span class="strong"><strong>int()</strong></span>.
       
   632     </p>
       
   633 <p id="x_1fa"></a>Let us look at an example.</p>
       
   634 <pre class="programlisting">&gt;&gt;&gt; intpal = int(pal)
       
   635 &gt;&gt;&gt; intpal
       
   636 121
       
   637 
       
   638 </pre>
       
   639 <p id="x_1fb"></a>In the previous example it was observed that 
       
   640       <span class="emphasis"><em>pal</em></span> was a string variable. Here using the 
       
   641       <span class="strong"><strong>int()</strong></span> method the string 
       
   642       <span class="emphasis"><em>pal</em></span> was converted to an integer variable.
       
   643     </p>
       
   644 <p id="x_1fc"></a>
       
   645       <span class="emphasis"><em>Try This Yourself:</em></span>
       
   646     </p>
       
   647 <pre class="programlisting">&gt;&gt;&gt; stringvar = raw_input("Enter a name:")
       
   648 Enter a name:Guido Van Rossum
       
   649 &gt;&gt;&gt; stringvar
       
   650 'Guido Van Rossum'
       
   651 &gt;&gt;&gt; numvar = int(stringvar)
       
   652 
       
   653 </pre>
       
   654 </div>
       
   655 </div>
       
   656 </div>
       
   657 </body>
       
   658 </html>