Some changes after the horrible problem of writing the same ch9 on all the html pages
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Chapter. intro </title> <link rel="stylesheet" href="/review/support/styles.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.74.3" /> <link rel="shortcut icon" type="image/png" href="/review/support/figs/favicon.png" /> <script type="text/javascript" src="/review/support/jquery-min.js"> </script> <script type="text/javascript" src="/review/support/form.js"> </script> <script type="text/javascript" src="/review/support/hsbook.js"> </script> </head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="chapter" title="Chapter 1. "><div class="titlepage"></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="article"><a href="#id2580245">Basic Python</a></span></dt><dd><dl><dt><span class="section"><a href="#id2388008">1. Introduction</a></span></dt><dt><span class="section"><a href="#id2631374">2. The Python Interpreter</a></span></dt><dd><dl><dt><span class="section"><a href="#id2631383">2.1. The Interactive Interpreter</a></span></dt><dt><span class="section"><a href="#id2631556">2.2. <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</a></span></dt></dl></dd><dt><span class="section"><a href="#id2631681">3. Editing and running a python file</a></span></dt><dt><span class="section"><a href="#id2631788">4. Basic Datatypes and operators in Python</a></span></dt><dd><dl><dt><span class="section"><a href="#id2631822">4.1. Numbers</a></span></dt><dt><span class="section"><a href="#id2631952">4.2. Variables</a></span></dt><dt><span class="section"><a href="#id2632000">4.3. Strings</a></span></dt><dt><span class="section"><a href="#id2632194">4.4. Boolean</a></span></dt></dl></dd><dt><span class="section"><a href="#id2632223">5. The <span class="strong"><strong>while</strong></span> loop</a></span></dt><dt><span class="section"><a href="#id2632260">6. The <span class="strong"><strong>if</strong></span> conditional</a></span></dt><dt><span class="section"><a href="#id2632330">7. <span class="strong"><strong>raw_input()</strong></span></a></span></dt><dt><span class="section"><a href="#id2632484">8. <span class="strong"><strong>int()</strong></span> method</a></span></dt></dl></dd></dl></div><div class="article" title="Basic Python"><div class="titlepage"><div><div><h2 class="title"><a name="id2580245"></a>Basic Python</h2></div></div><hr></div><div class="toc"><p><b>Table of Contents</b></p><dl><dt><span class="section"><a href="#id2388008">1. Introduction</a></span></dt><dt><span class="section"><a href="#id2631374">2. The Python Interpreter</a></span></dt><dd><dl><dt><span class="section"><a href="#id2631383">2.1. The Interactive Interpreter</a></span></dt><dt><span class="section"><a href="#id2631556">2.2. <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</a></span></dt></dl></dd><dt><span class="section"><a href="#id2631681">3. Editing and running a python file</a></span></dt><dt><span class="section"><a href="#id2631788">4. Basic Datatypes and operators in Python</a></span></dt><dd><dl><dt><span class="section"><a href="#id2631822">4.1. Numbers</a></span></dt><dt><span class="section"><a href="#id2631952">4.2. Variables</a></span></dt><dt><span class="section"><a href="#id2632000">4.3. Strings</a></span></dt><dt><span class="section"><a href="#id2632194">4.4. Boolean</a></span></dt></dl></dd><dt><span class="section"><a href="#id2632223">5. The <span class="strong"><strong>while</strong></span> loop</a></span></dt><dt><span class="section"><a href="#id2632260">6. The <span class="strong"><strong>if</strong></span> conditional</a></span></dt><dt><span class="section"><a href="#id2632330">7. <span class="strong"><strong>raw_input()</strong></span></a></span></dt><dt><span class="section"><a href="#id2632484">8. <span class="strong"><strong>int()</strong></span> method</a></span></dt></dl></div><p><a name="ch2intro_1"></a>This document is intended to be handed out at the end of the workshop. It hasbeen designed for Engineering students who are Python beginners and have basicprogramming skills. The focus is on basic numerics and plotting using Python.</p>The system requirements:<div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_2"></a>Python - version 2.5.x or newer.</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_3"></a>IPython</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_4"></a>Text editor - scite, vim, emacs or whatever you are comfortable with.</p></li></ul></div><div class="section" title="1. Introduction"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2388008"></a>1. Introduction</h2></div></div></div><p><a name="ch2intro_5"></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 nothingto 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 favouriteTV series.</p><p><a name="ch2intro_6"></a>Current stable version of Python is 2.6.x, although Python 3.0 is also the stableversion, it is not backwards compatible with the previous versions and is hencenot entirely popular at the moment. This material will focus on the 2.6.x series.</p><p><a name="ch2intro_7"></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 modifyand redistribute.</p><p><a name="ch2intro_8"></a>The Python docs define Python as "Python is an interpreted, object-oriented,high-level programming language with dynamic semantics." A more detailed summarycan be found at </p><div class="reference"><div class="titlepage"><hr></div>http://www.python.org/doc/essays/blurb.html</div><p>. Python is a language thathas been designed to help the programmer concentrate on solving the problem at handand not worry about the programming language idiosyncrasies.</p><p><a name="ch2intro_9"></a>Python is a highly cross platform compatible language on account of it being aninterpreted language. It is highly scalable and hence has been adapted to run onthe Nokia 60 series phones. Python has been designed to be readable and easy to use</p><p><a name="ch2intro_a"></a><span class="strong"><strong>Resources available for reference</strong></span></p><div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_b"></a>Web: </p><div class="reference"><div class="titlepage"><hr></div>http://www.python.org</div></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_c"></a>Doc: </p><div class="reference"><div class="titlepage"><hr></div>http://www.python.org/doc</div></li><li class="listitem" style="list-style-type: *">Free Tutorials:<div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_d"></a>Official Python Tutorial: </p><div class="reference"><div class="titlepage"><hr></div>http://docs.python.org/tut/tut.html</div></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_e"></a>Byte of Python: </p><div class="reference"><div class="titlepage"><hr></div>http://www.byteofpython.info/</div></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_f"></a>Dive into Python: </p><div class="reference"><div class="titlepage"><hr></div>http://diveintopython.org/</div></li></ul></div></li></ul></div><p><a name="ch2intro_10"></a><span class="strong"><strong>Advantages of Python - Why Python??</strong></span></p><div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_11"></a>Python has been designed for readability and ease of use. Its been designed insuch a fashion that it imposes readability on the programmer. Python does awaywith the braces and the semicolons and instead implements code blocks based onindentation, thus enhancing readability.</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_12"></a>Python is a high level, interpreted, modular and object oriented language.Python performs memory management on its own, thus the programmer need not botherabout allocating and deallocating memory to variables. Python provides extensibilityby providing modules which can be easily imported similar to headers in C andpackages in Java. Python is object oriented and hence provides all the object orientedcharacteristics such as inheritance, encapsulation and polymorphism.</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_13"></a>Python offers a highly powerful interactive programming interface in the formof the 'Interactive Interpreter' which will be discussed in more detail in thefollowing sections.</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_14"></a>Python provides a rich standard library and an extensive set of modules. Thepower of Python modules can be seen in this slightly exaggerated cartoon</p><div class="reference"><div class="titlepage"><hr></div>http://xkcd.com/353/</div></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_15"></a>Python interfaces well with most other programming languages such as C, C++and FORTRAN.</p></li></ul></div><p><a name="ch2intro_16"></a>Although, Python has one setback. Python is not fast as some of the compiledlanguages like C or C++. Yet, the amount of flexibility and power more than makeup for this setback.</p></div><div class="section" title="2. The Python Interpreter"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2631374"></a>2. The Python Interpreter</h2></div></div></div><div class="section" title="2.1. The Interactive Interpreter"><div class="titlepage"><div><div><h3 class="title"><a name="id2631383"></a>2.1. The Interactive Interpreter</h3></div></div></div><p><a name="ch2intro_17"></a>Typing <span class="emphasis"><em>python</em></span> at the shell prompt on any standard Unix/Gnu-Linux system andhitting the enter key fires up the Python 'Interactive Interpreter'. The Pythoninterpreter is one of the most integral features of Python. The prompt obtainedwhen the interactive interpreter is similar to what is shown below. The exactappearance might differ based on the version of Python being used. The <code class="literal">>>></code>thing shown is the python prompt. When something is typed at the prompt and theenter key is hit, the python interpreter interprets the command entered andperforms the appropriate action. All the examples presented in this document areto be tried hands on, on the interactive interpreter.</p><pre class="programlisting">Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)[GCC 4.3.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>></pre><p><a name="ch2intro_18"></a>Lets try with an example, type <code class="literal">print 'Hello, World!'</code> at the prompt and hitthe enter key.</p><pre class="programlisting">>>> print 'Hello, World!'Hello, World!</pre><p><a name="ch2intro_19"></a>This example was quite straight forward, and thus we have written our firstline of Python code. Now let us try typing something arbitrary at the prompt.For example:</p><pre class="programlisting">>>> arbit word File "<stdin>", line 1 arbit word ^SyntaxError: invalid syntax>>></pre><p><a name="ch2intro_1a"></a>The interpreter gave an error message saying that 'arbit word' was invalidsyntax which is valid. The interpreter is an amazing tool when learning toprogram in Python. The interpreter provides a help function that provides thenecessary documentation regarding all Python syntax, constructs, modules andobjects. Typing <span class="emphasis"><em>help()</em></span> at the prompt gives the following output:</p><pre class="programlisting">>>> help()Welcome to Python 2.5! This is the online help utility.If this is your first time using Python, you should definitely check outthe tutorial on the Internet at http://www.python.org/doc/tut/.Enter the name of any module, keyword, or topic to get help on writingPython programs and using Python modules. To quit this help utility andreturn to the interpreter, just type "quit".To get a list of available modules, keywords, or topics, type "modules","keywords", or "topics". Each module also comes with a one-line summaryof what it does; to list the modules whose summaries contain a given wordsuch as "spam", type "modules spam".help></pre><p><a name="ch2intro_1b"></a>As mentioned in the output, entering the name of any module, keyword or topicwill provide the documentation and help regarding the same through the onlinehelp utility. Pressing <span class="emphasis"><em>Ctrl+d</em></span> exits the help prompt and returns to thepython prompt.</p><p><a name="ch2intro_1c"></a>Let us now try a few examples at the python interpreter.</p><p><a name="ch2intro_1d"></a>Eg 1:</p><pre class="programlisting">>>> print 'Hello, python!'Hello, python!>>></pre><p><a name="ch2intro_1e"></a>Eg 2:</p><pre class="programlisting">>>> print 4321*5678902453852690>>></pre><p><a name="ch2intro_1f"></a>Eg 3:</p><pre class="programlisting">>>> 4321*5678902453852690L>>></pre><pre class="programlisting">Note: Notice the 'L' at the end of the output. The 'L' signifies that theoutput of the operation is of type *long*. It was absent in the previousexample because we used the print statement. This is because *print* formatsthe output before displaying.</pre><p><a name="ch2intro_20"></a>Eg 4:</p><pre class="programlisting">>>> big = 12345678901234567890 ** 3>>> print big1881676372353657772490265749424677022198701224860897069000>>></pre><pre class="programlisting">This example is to show that unlike in C or C++ there is no limit on thevalue of an integer.</pre><p><a name="ch2intro_21"></a>Try this on the interactive interpreter:<code class="literal">import this</code></p><p><a name="ch2intro_22"></a><span class="emphasis"><em>Hint: The output gives an idea of Power of Python</em></span></p></div><div class="section" title="2.2. ipython - An enhanced interactive Python interpreter"><div class="titlepage"><div><div><h3 class="title"><a name="id2631556"></a>2.2. <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</h3></div></div></div><p><a name="ch2intro_23"></a>The power and the importance of the interactive interpreter was the highlightof the previous section. This section provides insight into the enhancedinterpreter with more advanced set of features called <span class="strong"><strong>ipython</strong></span>. Entering<span class="emphasis"><em>ipython</em></span> at the shell prompt fires up the interactive interpreter.</p><pre class="programlisting">$ ipythonPython 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)Type "copyright", "credits" or "license" for more information.IPython 0.8.4 -- An enhanced Interactive Python.? -> Introduction and overview of IPython's features.%quickref -> Quick reference.help -> Python's own help system.object? -> Details about 'object'. ?object also works, ?? prints more.In [1]:</pre><p><a name="ch2intro_24"></a>This is the output obtained upon firing ipython. The exact appearance maychange based on the Python version installed. The following are some of thevarious features provided by <span class="strong"><strong>ipython</strong></span>:</p><p><a name="ch2intro_25"></a>Suggestions - ipython provides suggestions of the possible methods andoperations available for the given python object.</p><p><a name="ch2intro_26"></a>Eg 5:</p><pre class="programlisting">In [4]: a = 6In [5]: a.a.__abs__ a.__divmod__ a.__index__ a.__neg__ a.__rand__ a.__rmod__ a.__rxor__a.__add__ a.__doc__ a.__init__ a.__new__ a.__rdiv__ a.__rmul__ a.__setattr__a.__and__ a.__float__ a.__int__ a.__nonzero__ a.__rdivmod__ a.__ror__ a.__str__a.__class__ a.__floordiv__ a.__invert__ a.__oct__ a.__reduce__ a.__rpow__ a.__sub__a.__cmp__ a.__getattribute__ a.__long__ a.__or__ a.__reduce_ex__ a.__rrshift__ a.__truediv__a.__coerce__ a.__getnewargs__ a.__lshift__ a.__pos__ a.__repr__ a.__rshift__ a.__xor__a.__delattr__ a.__hash__ a.__mod__ a.__pow__ a.__rfloordiv__ a.__rsub__a.__div__ a.__hex__ a.__mul__ a.__radd__ a.__rlshift__ a.__rtruediv__</pre><p><a name="ch2intro_27"></a>In this example, we initialized 'a' (a variable - a concept that will bediscussed in the subsequent sections.) to 6. In the next line when the <span class="emphasis"><em>tab</em></span> keyis pressed after typing '<span class="emphasis"><em>a.</em></span>' ipython displays the set of all possible methodsthat are applicable on the object 'a' (an integer in this context). Ipythonprovides many such datatype specific features which will be presented in thefurther sections as and when the datatypes are introduced.</p></div></div><div class="section" title="3. Editing and running a python file"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2631681"></a>3. Editing and running a python file</h2></div></div></div><p><a name="ch2intro_28"></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 andexperiment with small code snippets, its main disadvantage is that everythingwritten in the interpreter is lost once its quit. Most of the times a program isused by people other than the author. So the programs have to be available insome form suitable for distribution, and hence they are written in files. Thissection will focus on editing and running python files. Start by opening a texteditor ( 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 <span class="strong"><strong>.py</strong></span>(python files have an extension of .py). Once done with the editing, save thefile and exit the editor.</p><p><a name="ch2intro_29"></a>Let us look at a simple example of calculating the gcd of 2 numbers using Python:</p><p><a name="ch2intro_2a"></a><span class="strong"><strong>Creating the first python script(file)</strong></span></p><pre class="programlisting">$ emacs gcd.py def gcd(x,y): if x % y == 0: return y return gcd(y, x%y) print gcd(72, 92)</pre><p><a name="ch2intro_2b"></a>To run the script, open the shell prompt, navigate to the directory thatcontains the python file and run <code class="literal">python <filename.py></code> at the prompt ( in thiscase filename is gcd.py )</p><p><a name="ch2intro_2c"></a><span class="strong"><strong>Running the python script</strong></span></p><pre class="programlisting">$ python gcd.py4$</pre><p><a name="ch2intro_2d"></a>Another method to run a python script would be to include the line</p><p><a name="ch2intro_2e"></a><code class="literal">#! /usr/bin/python</code></p><p><a name="ch2intro_2f"></a>at the beginning of the python file and then make the file executable by</p><p><a name="ch2intro_30"></a>$ chmod a+x <span class="emphasis"><em>filename.py</em></span></p><p><a name="ch2intro_31"></a>Once this is done, the script can be run as a standalone program as follows:</p><p><a name="ch2intro_32"></a>$ ./<span class="emphasis"><em>filename.py</em></span></p></div><div class="section" title="4. Basic Datatypes and operators in Python"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2631788"></a>4. Basic Datatypes and operators in Python</h2></div></div></div><p><a name="ch2intro_33"></a>Python provides the following set of basic datatypes.</p><div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_34"></a>Numbers: int, float, long, complex</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_35"></a>Strings</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_36"></a>Boolean</p></li></ul></div><div class="section" title="4.1. Numbers"><div class="titlepage"><div><div><h3 class="title"><a name="id2631822"></a>4.1. Numbers</h3></div></div></div><p><a name="ch2intro_37"></a>Numbers were introduced in the examples presented in the interactive interpretersection. Numbers include types as mentioned earlier viz., int (integers), float(floating point numbers), long (large integers), complex (complex numbers withreal and imaginary parts). Python is not a strongly typed language, which meansthe type of a variable need not mentioned during its initialization. Let us lookat a few examples.</p><p><a name="ch2intro_38"></a>Eg 6:</p><pre class="programlisting">>>> a = 1 #here a is an integer variable</pre><p><a name="ch2intro_39"></a>Eg 7:</p><pre class="programlisting">>>> lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long>>> lng122333444455555666666777777788888888999999999L #notice the trailing 'L'>>> print lng122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L'>>> lng+1122333444455555666666777777788888889000000000L</pre><p><a name="ch2intro_3a"></a>Long numbers are the same as integers in almost all aspects. They can be used inoperations 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 variablewith the 'L' whereas <code class="literal">print lng</code> displays without the 'L'. This is because printformats the output before printing. Also in the example, notice that adding aninteger to a long does not give any errors and the result is as expected. So forall practical purposes longs can be treated as ints.</p><p><a name="ch2intro_3b"></a>Eg 8:</p><pre class="programlisting">>>> fl = 3.14159 #fl is a float variable>>> e = 1.234e-4 #e is also a float variable, specified in the exponential form>>> a = 1>>> b = 2>>> a/b #integer division0>>> a/fl #floating point division0.31831015504887655>>> e/fl3.9279473133031364e-05</pre><p><a name="ch2intro_3c"></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 thisexample 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><p><a name="ch2intro_3d"></a>Eg 9:</p><pre class="programlisting">>>> cplx = 3 + 4j #cplx is a complex variable>>> cplx(3+4j)>>> print cplx.real #prints the real part of the complex number3.0>>> print cplx.imag #prints the imaginary part of the complex number4.0>>> print cplx*fl #multiplies the real and imag parts of the complex number with the multiplier(9.42477+12.56636j)>>> abs(cplx) #returns the absolute value of the complex number5.0</pre><p><a name="ch2intro_3e"></a>Python provides a datatype for complex numbers. Complex numbers are initializedas shown in the example above. The <span class="emphasis"><em>real</em></span> and <span class="emphasis"><em>imag</em></span> operators return the real andimaginary parts of the complex number as shown. The <span class="emphasis"><em>abs()</em></span> returns the absolutevalue of the complex number.</p></div><div class="section" title="4.2. Variables"><div class="titlepage"><div><div><h3 class="title"><a name="id2631952"></a>4.2. Variables</h3></div></div></div><p><a name="ch2intro_3f"></a>Variables are just names that represent a value. Variables have already beenintroduced in the various examples from the previous sections. Certain rules aboutusing variables:</p><div class="itemizedlist"><ul class="itemizedlist" type="*"><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_40"></a>Variables have to be initialized or assigned a value before being used.</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_41"></a>Variable names can consist of letters, digits and underscores(_).</p></li><li class="listitem" style="list-style-type: *"><p><a name="ch2intro_42"></a>Variable names cannot begin with digits, but can contain digits in them.</p></li></ul></div><p><a name="ch2intro_43"></a>In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx'are all variables of various datatypes.</p><pre class="programlisting">Note: Python is not a strongly typed language and hence an integer variable can at alater stage be used as a float variable as well.</pre></div><div class="section" title="4.3. Strings"><div class="titlepage"><div><div><h3 class="title"><a name="id2632000"></a>4.3. Strings</h3></div></div></div><p><a name="ch2intro_44"></a>Strings are one of the essential data structures of any programming language.The <code class="literal">print "Hello, World!"</code> program was introduced in the earlier section, andthe <span class="emphasis"><em>"Hello, World!"</em></span> in the print statement is a string. A string is basicallya set of characters. Strings can be represented in various ways shown below:</p><pre class="programlisting">s = 'this is a string' # a string variable can be represented using single quotess = 'This one has "quotes" inside!' # The string can have quotes inside it as showns = "I have 'single-quotes' inside!"l = "A string spanning many lines\one more line\yet another" # a string can span more than a single line.t = """A triple quoted string does # another way of representing multiline strings.not need to be escaped at the end and"can have nested quotes" etc."""</pre><p><a name="ch2intro_45"></a>Try the following on the interpreter:<code class="literal">s = 'this is a string with 'quotes' of similar kind'</code></p><p><a name="ch2intro_46"></a><span class="strong"><strong>Exercise: How to use single quotes within single quotes in a string as shownin the above example without getting an error?</strong></span></p><div class="section" title="4.3.1. String operations"><div class="titlepage"><div><div><h4 class="title"><a name="id2632051"></a>4.3.1. String operations</h4></div></div></div><p><a name="ch2intro_47"></a>A few basic string operations are presented here.</p><p><a name="ch2intro_48"></a><span class="strong"><strong>String concatenation</strong></span>String concatenation is done by simple addition of two strings.</p><pre class="programlisting">>>> x = 'Hello'>>> y = ' Python'>>> print x+yHello Python</pre><p><a name="ch2intro_49"></a><span class="emphasis"><em>Try this yourself:</em></span></p><pre class="programlisting">>>> somenum = 13>>> print x+somenum</pre><p><a name="ch2intro_4a"></a>The problem with the above example is that here a string variable and an integervariable are trying to be concantenated. To obtain the desired result from theabove example the str(), repr() and the `` can be used.</p><p><a name="ch2intro_4b"></a><span class="strong"><strong>str()</strong></span> simply converts a value to a string in a reasonable form.<span class="strong"><strong>repr()</strong></span> creates a string that is a representation of the value.</p><p><a name="ch2intro_4c"></a>The difference can be seen in the example shown below:</p><pre class="programlisting">>>> str(1000000000000000000000000000000000000000000000000L)'1000000000000000000000000000000000000000000000000'>>> repr(1000000000000000000000000000000000000000000000000L)'1000000000000000000000000000000000000000000000000L'</pre><p><a name="ch2intro_4d"></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 usingrepr(value) is <code class="literal">`value`</code>.</p><p><a name="ch2intro_4e"></a>A few more examples:</p><pre class="programlisting">>>> x = "Let's go \nto Pycon">>> print xLet's goto Pycon</pre><p><a name="ch2intro_4f"></a>In the above example, notice that the 'n'(newline) character is formatted andthe string is printed on two lines. The strings discussed until now were normalstrings. Other than these there are two other types of strings namely, raw stringsand unicode strings.</p><p><a name="ch2intro_50"></a><span class="strong"><strong>Raw strings</strong></span> are strings which are unformatted, that is the backslashes() arenot parsed and are left as it is in the string. Raw strings are represented withan 'r' at the start of a string.Let us look at an example</p><pre class="programlisting">>>> x = r"Let's go \nto Pycon">>> print xLet's go \nto Pycon</pre><p><a name="ch2intro_51"></a>Note: The 'n' is not being parsed into a new line and is left as it is.</p><p><a name="ch2intro_52"></a><span class="emphasis"><em>Try this yourself:</em></span></p><pre class="programlisting">>>> x = r"Let's go to Pycon\"</pre><p><a name="ch2intro_53"></a><span class="strong"><strong>Unicode strings</strong></span> are strings where the characters are Unicode characters asopposed to ASCII characters. Unicode strings are represented with a 'u' at thestart of the string.Let us look at an example:</p><pre class="programlisting">>>> x = u"Let's go to Pycon!">>> print xLet's go to Pycon!</pre></div></div><div class="section" title="4.4. Boolean"><div class="titlepage"><div><div><h3 class="title"><a name="id2632194"></a>4.4. Boolean</h3></div></div></div><p><a name="ch2intro_54"></a>Python also provides special Boolean datatype. A boolean variable can assume avalue of either <span class="emphasis"><em>True</em></span> or <span class="emphasis"><em>False</em></span> (Note the capitalizations).</p><p><a name="ch2intro_55"></a>Let us look at examples:</p><pre class="programlisting">>>> t = True>>> f = not t>>> print fFalse>>> f or tTrue>>> f and tFalse</pre></div></div><div class="section" title="5. The while loop"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2632223"></a>5. The <span class="strong"><strong>while</strong></span> loop</h2></div></div></div><p><a name="ch2intro_56"></a>The Python <span class="strong"><strong>while</strong></span> loop is similar to the C/C++ while loop. The syntax is asfollows:</p><pre class="programlisting">statement 0while condition: statement 1 #while block statement 2 #while blockstatement 3 #outside the while block.</pre><p><a name="ch2intro_57"></a>Let us look at an example:</p><pre class="programlisting">>>> x = 1>>> while x <= 5:... print x... x += 1...12345</pre></div><div class="section" title="6. The if conditional"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2632260"></a>6. The <span class="strong"><strong>if</strong></span> conditional</h2></div></div></div><p><a name="ch2intro_58"></a>The Python <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 ifblock are executed.</p><p><a name="ch2intro_59"></a>If the first block is not executed on account of the condition not being satisfied,the set of statements in the <span class="strong"><strong>else</strong></span> block are executed.</p><p><a name="ch2intro_5a"></a>The <span class="strong"><strong>elif</strong></span> block provides the functionality of evaluation of multiple conditionsas shown in the example.</p><p><a name="ch2intro_5b"></a>The syntax is as follows:</p><pre class="programlisting">if condition : statement_1 statement_2elif condition: statement_3 statement_4else: statement_5 statement_6</pre><p><a name="ch2intro_5c"></a>Let us look at an example:</p><pre class="programlisting">>>> n = raw_input("Input a number:")>>> if n < 0: print n," is negative" elif n > 0: print n," is positive" else: print n, " is 0"</pre></div><div class="section" title="7. raw_input()"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2632330"></a>7. <span class="strong"><strong>raw_input()</strong></span></h2></div></div></div><p><a name="ch2intro_5d"></a>In the previous example we saw the call to the raw_input() subroutine.The <span class="strong"><strong>raw_input()</strong></span> method is used to take user inputs through the console.Unlike <span class="strong"><strong>input()</strong></span> which assumes the data entered by the user as a standard pythonexpression, <span class="strong"><strong>raw_input()</strong></span> treats all the input data as raw data and convertseverything into a string. To illustrate this let us look at an example.</p><pre class="programlisting">>>> input("Enter a number thats a palindrome:")Enter a number thats a palindrome:121121>>> input("Enter your name:")Enter your name:PythonFreakTraceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module>NameError: name 'PythonFreak' is not defined</pre><p><a name="ch2intro_5e"></a>As shown above the <span class="strong"><strong>input()</strong></span> assumes that the data entered is a valid Pythonexpression. In the first call it prompts for an integer input and when enteredit accepts the integer as an integer, whereas in the second call, when the stringis entered without the quotes, <span class="strong"><strong>input()</strong></span> assumes that the entered data is a validPython expression and hence it raises and exception saying PythonFreak is notdefined.</p><pre class="programlisting">>>> input("Enter your name:")Enter your name:'PythonFreak''PythonFreak'>>></pre><p><a name="ch2intro_5f"></a>Here the name is accepted because its entered as a string (within quotes). Butits unreasonable to go on using quotes each time a string is entered. Hence thealternative is to use <span class="strong"><strong>raw_input()</strong></span>.</p><p><a name="ch2intro_60"></a>Let us now look at how <span class="strong"><strong>raw_input()</strong></span> operates with an example.</p><pre class="programlisting">>>> raw_input("Enter your name:")Enter your name:PythonFreak'PythonFreak'</pre><p><a name="ch2intro_61"></a>Observe that the <span class="strong"><strong>raw_input()</strong></span> is converting it into a string all by itself.</p><pre class="programlisting">>>> pal = raw_input("Enter a number thats a palindrome:")Enter a number thats a palindrome:121'121'</pre><p><a name="ch2intro_62"></a>Observe that <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:</p><pre class="programlisting">>>> pal = raw_input("Enter a number thats a palindrome:")Enter a number thats a palindrome:121>>> pal + 2Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects>>> pal'121'</pre><p><a name="ch2intro_63"></a>Observe here that the variable <span class="emphasis"><em>pal</em></span> is a string and hence integer operationscannot be performed on it. Hence the exception is raised.</p></div><div class="section" title="8. int() method"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="id2632484"></a>8. <span class="strong"><strong>int()</strong></span> method</h2></div></div></div><p><a name="ch2intro_64"></a>Generally for computing purposes, the data used is not strings or raw data buton integers, floats and similar mathematical data structures. The data obtainedfrom <span class="strong"><strong>raw_input()</strong></span> is raw data in the form of strings. In order to obtain integersfrom strings we use the method <span class="strong"><strong>int()</strong></span>.</p><p><a name="ch2intro_65"></a>Let us look at an example.</p><pre class="programlisting">>>> intpal = int(pal)>>> intpal121</pre><p><a name="ch2intro_66"></a>In the previous example it was observed that <span class="emphasis"><em>pal</em></span> was a string variable. Hereusing the <span class="strong"><strong>int()</strong></span> method the string <span class="emphasis"><em>pal</em></span> was converted to an integer variable.</p><p><a name="ch2intro_67"></a><span class="emphasis"><em>Try This Yourself:</em></span></p><pre class="programlisting">>>> stringvar = raw_input("Enter a name:")Enter a name:Guido Van Rossum>>> stringvar'Guido Van Rossum'>>> numvar = int(stringvar)</pre></div></div></div></body></html>