1 <html> |
|
2 <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> |
|
3 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="chapter" id="ch2intro"> |
|
4 <div class="titlepage"></div> |
|
5 <div class="toc"> |
|
6 <p><b>Table of Contents</b></p> |
|
7 <dl> |
|
8 <dt><span class="article"><a href="#id2915639">Basic Python</a></span></dt> |
|
9 <dd><dl> |
|
10 <dt><span class="section"><a href="#id2723402">1. Introduction</a></span></dt> |
|
11 <dt><span class="section"><a href="#id2966769">2. The Python Interpreter</a></span></dt> |
|
12 <dd><dl> |
|
13 <dt><span class="section"><a href="#id2966777">2.1. The Interactive Interpreter</a></span></dt> |
|
14 <dt><span class="section"><a href="#id2966950">2.2. <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</a></span></dt> |
|
15 </dl></dd> |
|
16 <dt><span class="section"><a href="#id2967075">3. Editing and running a python file</a></span></dt> |
|
17 <dt><span class="section"><a href="#id2967182">4. Basic Datatypes and operators in Python</a></span></dt> |
|
18 <dd><dl> |
|
19 <dt><span class="section"><a href="#id2967216">4.1. Numbers</a></span></dt> |
|
20 <dt><span class="section"><a href="#id2967346">4.2. Variables</a></span></dt> |
|
21 <dt><span class="section"><a href="#id2967394">4.3. Strings</a></span></dt> |
|
22 <dt><span class="section"><a href="#id2967588">4.4. Boolean</a></span></dt> |
|
23 </dl></dd> |
|
24 <dt><span class="section"><a href="#id2967617">5. The <span class="strong"><strong>while</strong></span> loop</a></span></dt> |
|
25 <dt><span class="section"><a href="#id2967654">6. The <span class="strong"><strong>if</strong></span> conditional</a></span></dt> |
|
26 <dt><span class="section"><a href="#id2967723">7. <span class="strong"><strong>raw_input()</strong></span></a></span></dt> |
|
27 <dt><span class="section"><a href="#id2967877">8. <span class="strong"><strong>int()</strong></span> method</a></span></dt> |
|
28 </dl></dd> |
|
29 </dl> |
|
30 </div> |
|
31 <div class="article" title="Basic Python"> |
|
32 <div class="titlepage"> |
|
33 <div><div><h2 class="title"> |
|
34 <a name="id2915639"></a>Basic Python</h2></div></div> |
|
35 <hr /> |
|
36 </div> |
|
37 <div class="toc"> |
|
38 <p><b>Table of Contents</b></p> |
|
39 <dl> |
|
40 <dt><span class="section"><a href="#id2723402">1. Introduction</a></span></dt> |
|
41 <dt><span class="section"><a href="#id2966769">2. The Python Interpreter</a></span></dt> |
|
42 <dd><dl> |
|
43 <dt><span class="section"><a href="#id2966777">2.1. The Interactive Interpreter</a></span></dt> |
|
44 <dt><span class="section"><a href="#id2966950">2.2. <span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</a></span></dt> |
|
45 </dl></dd> |
|
46 <dt><span class="section"><a href="#id2967075">3. Editing and running a python file</a></span></dt> |
|
47 <dt><span class="section"><a href="#id2967182">4. Basic Datatypes and operators in Python</a></span></dt> |
|
48 <dd><dl> |
|
49 <dt><span class="section"><a href="#id2967216">4.1. Numbers</a></span></dt> |
|
50 <dt><span class="section"><a href="#id2967346">4.2. Variables</a></span></dt> |
|
51 <dt><span class="section"><a href="#id2967394">4.3. Strings</a></span></dt> |
|
52 <dt><span class="section"><a href="#id2967588">4.4. Boolean</a></span></dt> |
|
53 </dl></dd> |
|
54 <dt><span class="section"><a href="#id2967617">5. The <span class="strong"><strong>while</strong></span> loop</a></span></dt> |
|
55 <dt><span class="section"><a href="#id2967654">6. The <span class="strong"><strong>if</strong></span> conditional</a></span></dt> |
|
56 <dt><span class="section"><a href="#id2967723">7. <span class="strong"><strong>raw_input()</strong></span></a></span></dt> |
|
57 <dt><span class="section"><a href="#id2967877">8. <span class="strong"><strong>int()</strong></span> method</a></span></dt> |
|
58 </dl> |
|
59 </div> |
|
60 <p id="ch2intro_1">This document is intended to be handed out at the end of the workshop. It has |
|
61 been designed for Engineering students who are Python beginners and have basic |
|
62 programming skills. The focus is on basic numerics and plotting using Python.</p>The system requirements:<div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
63 <li class="listitem" style="list-style-type: *"><p id="ch2intro_2">Python - version 2.5.x or newer.</p></li> |
|
64 <li class="listitem" style="list-style-type: *"><p id="ch2intro_3">IPython</p></li> |
|
65 <li class="listitem" style="list-style-type: *"><p id="ch2intro_4">Text editor - scite, vim, emacs or whatever you are comfortable with.</p></li> |
|
66 </ul></div> |
|
67 <div class="section" title="1.Introduction"> |
|
68 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
69 <a name="id2723402"></a>1.Introduction</h2></div></div></div> |
|
70 <p id="ch2intro_5">The Python programming language was created by a dutch named Guido van Rossum. |
|
71 The idea of Python was conceived in December 1989. The name Python has nothing |
|
72 to do with the reptilian, but its been named after the 70s comedy series |
|
73 "Monty Python's Flying Circus", since it happens to be Guido's favourite |
|
74 TV series.</p> |
|
75 <p id="ch2intro_6">Current stable version of Python is 2.6.x, although Python 3.0 is also the stable |
|
76 version, it is not backwards compatible with the previous versions and is hence |
|
77 not entirely popular at the moment. This material will focus on the 2.6.x series.</p> |
|
78 <p id="ch2intro_7">Python is licensed under the Python Software Foundation License (PSF License) |
|
79 which is GPL compatible Free Software license (excepting license version 1.6 and 2.0) |
|
80 It is a no strings attached license, which means the source code is free to modify |
|
81 and redistribute.</p> |
|
82 <p id="ch2intro_8">The Python docs define Python as "Python is an interpreted, object-oriented, |
|
83 high-level programming language with dynamic semantics." A more detailed summary |
|
84 can be found at </p> |
|
85 <div class="reference"> |
|
86 <div class="titlepage"><hr /></div>http://www.python.org/doc/essays/blurb.html</div> |
|
87 <p>. Python is a language that |
|
88 has been designed to help the programmer concentrate on solving the problem at hand |
|
89 and not worry about the programming language idiosyncrasies.</p> |
|
90 <p id="ch2intro_9">Python is a highly cross platform compatible language on account of it being an |
|
91 interpreted language. It is highly scalable and hence has been adapted to run on |
|
92 the Nokia 60 series phones. Python has been designed to be readable and easy to use</p> |
|
93 <p id="ch2intro_a"><span class="strong"><strong>Resources available for reference</strong></span></p> |
|
94 <div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
95 <li class="listitem" style="list-style-type: *"> |
|
96 <p id="ch2intro_b">Web: </p> |
|
97 <div class="reference"> |
|
98 <div class="titlepage"><hr /></div>http://www.python.org</div> |
|
99 </li> |
|
100 <li class="listitem" style="list-style-type: *"> |
|
101 <p id="ch2intro_c">Doc: </p> |
|
102 <div class="reference"> |
|
103 <div class="titlepage"><hr /></div>http://www.python.org/doc</div> |
|
104 </li> |
|
105 <li class="listitem" style="list-style-type: *">Free Tutorials:<div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
106 <li class="listitem" style="list-style-type: *"> |
|
107 <p id="ch2intro_d">Official Python Tutorial: </p> |
|
108 <div class="reference"> |
|
109 <div class="titlepage"><hr /></div>http://docs.python.org/tut/tut.html</div> |
|
110 </li> |
|
111 <li class="listitem" style="list-style-type: *"> |
|
112 <p id="ch2intro_e">Byte of Python: </p> |
|
113 <div class="reference"> |
|
114 <div class="titlepage"><hr /></div>http://www.byteofpython.info/</div> |
|
115 </li> |
|
116 <li class="listitem" style="list-style-type: *"> |
|
117 <p id="ch2intro_f">Dive into Python: </p> |
|
118 <div class="reference"> |
|
119 <div class="titlepage"><hr /></div>http://diveintopython.org/</div> |
|
120 </li> |
|
121 </ul></div> |
|
122 </li> |
|
123 </ul></div> |
|
124 <p id="ch2intro_10"><span class="strong"><strong>Advantages of Python - Why Python??</strong></span></p> |
|
125 <div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
126 <li class="listitem" style="list-style-type: *"><p id="ch2intro_11">Python has been designed for readability and ease of use. Its been designed in |
|
127 such a fashion that it imposes readability on the programmer. Python does away |
|
128 with the braces and the semicolons and instead implements code blocks based on |
|
129 indentation, thus enhancing readability.</p></li> |
|
130 <li class="listitem" style="list-style-type: *"><p id="ch2intro_12">Python is a high level, interpreted, modular and object oriented language. |
|
131 Python performs memory management on its own, thus the programmer need not bother |
|
132 about allocating and deallocating memory to variables. Python provides extensibility |
|
133 by providing modules which can be easily imported similar to headers in C and |
|
134 packages in Java. Python is object oriented and hence provides all the object oriented |
|
135 characteristics such as inheritance, encapsulation and polymorphism.</p></li> |
|
136 <li class="listitem" style="list-style-type: *"><p id="ch2intro_13">Python offers a highly powerful interactive programming interface in the form |
|
137 of the 'Interactive Interpreter' which will be discussed in more detail in the |
|
138 following sections.</p></li> |
|
139 <li class="listitem" style="list-style-type: *"> |
|
140 <p id="ch2intro_14">Python provides a rich standard library and an extensive set of modules. The |
|
141 power of Python modules can be seen in this slightly exaggerated cartoon |
|
142 </p> |
|
143 <div class="reference"> |
|
144 <div class="titlepage"><hr /></div>http://xkcd.com/353/</div> |
|
145 </li> |
|
146 <li class="listitem" style="list-style-type: *"><p id="ch2intro_15">Python interfaces well with most other programming languages such as C, C++ |
|
147 and FORTRAN.</p></li> |
|
148 </ul></div> |
|
149 <p id="ch2intro_16">Although, Python has one setback. Python is not fast as some of the compiled |
|
150 languages like C or C++. Yet, the amount of flexibility and power more than make |
|
151 up for this setback.</p> |
|
152 </div> |
|
153 <div class="section" title="2.The Python Interpreter"> |
|
154 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
155 <a name="id2966769"></a>2.The Python Interpreter</h2></div></div></div> |
|
156 <div class="section" title="2.1.The Interactive Interpreter"> |
|
157 <div class="titlepage"><div><div><h3 class="title"> |
|
158 <a name="id2966777"></a>2.1.The Interactive Interpreter</h3></div></div></div> |
|
159 <p id="ch2intro_17">Typing <span class="emphasis"><em>python</em></span> at the shell prompt on any standard Unix/Gnu-Linux system and |
|
160 hitting the enter key fires up the Python 'Interactive Interpreter'. The Python |
|
161 interpreter is one of the most integral features of Python. The prompt obtained |
|
162 when the interactive interpreter is similar to what is shown below. The exact |
|
163 appearance might differ based on the version of Python being used. The <code class="literal">>>></code> |
|
164 thing shown is the python prompt. When something is typed at the prompt and the |
|
165 enter key is hit, the python interpreter interprets the command entered and |
|
166 performs the appropriate action. All the examples presented in this document are |
|
167 to be tried hands on, on the interactive interpreter.</p> |
|
168 <pre class="programlisting"> |
|
169 Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) |
|
170 [GCC 4.3.2] on linux2 |
|
171 Type "help", "copyright", "credits" or "license" for more information. |
|
172 >>></pre> |
|
173 <p id="ch2intro_18">Lets try with an example, type <code class="literal">print 'Hello, World!'</code> at the prompt and hit |
|
174 the enter key.</p> |
|
175 <pre class="programlisting"> |
|
176 >>> print 'Hello, World!' |
|
177 Hello, World!</pre> |
|
178 <p id="ch2intro_19">This example was quite straight forward, and thus we have written our first |
|
179 line of Python code. Now let us try typing something arbitrary at the prompt. |
|
180 For example:</p> |
|
181 <pre class="programlisting"> |
|
182 >>> arbit word |
|
183 File "<stdin>", line 1 |
|
184 arbit word |
|
185 ^ |
|
186 SyntaxError: invalid syntax |
|
187 >>></pre> |
|
188 <p id="ch2intro_1a">The interpreter gave an error message saying that 'arbit word' was invalid |
|
189 syntax which is valid. The interpreter is an amazing tool when learning to |
|
190 program in Python. The interpreter provides a help function that provides the |
|
191 necessary documentation regarding all Python syntax, constructs, modules and |
|
192 objects. Typing <span class="emphasis"><em>help()</em></span> at the prompt gives the following output:</p> |
|
193 <pre class="programlisting"> |
|
194 >>> help() |
|
195 |
|
196 Welcome to Python 2.5! This is the online help utility. |
|
197 |
|
198 If this is your first time using Python, you should definitely check out |
|
199 the tutorial on the Internet at http://www.python.org/doc/tut/. |
|
200 |
|
201 Enter the name of any module, keyword, or topic to get help on writing |
|
202 Python programs and using Python modules. To quit this help utility and |
|
203 return to the interpreter, just type "quit". |
|
204 |
|
205 To get a list of available modules, keywords, or topics, type "modules", |
|
206 "keywords", or "topics". Each module also comes with a one-line summary |
|
207 of what it does; to list the modules whose summaries contain a given word |
|
208 such as "spam", type "modules spam". |
|
209 |
|
210 help></pre> |
|
211 <p id="ch2intro_1b">As mentioned in the output, entering the name of any module, keyword or topic |
|
212 will provide the documentation and help regarding the same through the online |
|
213 help utility. Pressing <span class="emphasis"><em>Ctrl+d</em></span> exits the help prompt and returns to the |
|
214 python prompt.</p> |
|
215 <p id="ch2intro_1c">Let us now try a few examples at the python interpreter.</p> |
|
216 <p id="ch2intro_1d">Eg 1:</p> |
|
217 <pre class="programlisting"> |
|
218 >>> print 'Hello, python!' |
|
219 Hello, python! |
|
220 >>></pre> |
|
221 <p id="ch2intro_1e">Eg 2:</p> |
|
222 <pre class="programlisting"> |
|
223 >>> print 4321*567890 |
|
224 2453852690 |
|
225 >>></pre> |
|
226 <p id="ch2intro_1f">Eg 3:</p> |
|
227 <pre class="programlisting"> |
|
228 >>> 4321*567890 |
|
229 2453852690L |
|
230 >>></pre> |
|
231 <pre class="programlisting"> |
|
232 Note: Notice the 'L' at the end of the output. The 'L' signifies that the |
|
233 output of the operation is of type *long*. It was absent in the previous |
|
234 example because we used the print statement. This is because *print* formats |
|
235 the output before displaying.</pre> |
|
236 <p id="ch2intro_20">Eg 4:</p> |
|
237 <pre class="programlisting"> |
|
238 >>> big = 12345678901234567890 ** 3 |
|
239 >>> print big |
|
240 1881676372353657772490265749424677022198701224860897069000 |
|
241 >>></pre> |
|
242 <pre class="programlisting"> |
|
243 This example is to show that unlike in C or C++ there is no limit on the |
|
244 value of an integer.</pre> |
|
245 <p id="ch2intro_21">Try this on the interactive interpreter: |
|
246 <code class="literal">import this</code></p> |
|
247 <p id="ch2intro_22"><span class="emphasis"><em>Hint: The output gives an idea of Power of Python</em></span></p> |
|
248 </div> |
|
249 <div class="section" title="2.2.ipython - An enhanced interactive Python interpreter"> |
|
250 <div class="titlepage"><div><div><h3 class="title"> |
|
251 <a name="id2966950"></a>2.2.<span class="emphasis"><em>ipython</em></span> - An enhanced interactive Python interpreter</h3></div></div></div> |
|
252 <p id="ch2intro_23">The power and the importance of the interactive interpreter was the highlight |
|
253 of the previous section. This section provides insight into the enhanced |
|
254 interpreter with more advanced set of features called <span class="strong"><strong>ipython</strong></span>. Entering |
|
255 <span class="emphasis"><em>ipython</em></span> at the shell prompt fires up the interactive interpreter.</p> |
|
256 <pre class="programlisting"> |
|
257 $ ipython |
|
258 Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) |
|
259 Type "copyright", "credits" or "license" for more information. |
|
260 |
|
261 IPython 0.8.4 -- An enhanced Interactive Python. |
|
262 ? -> Introduction and overview of IPython's features. |
|
263 %quickref -> Quick reference. |
|
264 help -> Python's own help system. |
|
265 object? -> Details about 'object'. ?object also works, ?? prints more. |
|
266 |
|
267 In [1]:</pre> |
|
268 <p id="ch2intro_24">This is the output obtained upon firing ipython. The exact appearance may |
|
269 change based on the Python version installed. The following are some of the |
|
270 various features provided by <span class="strong"><strong>ipython</strong></span>:</p> |
|
271 <p id="ch2intro_25">Suggestions - ipython provides suggestions of the possible methods and |
|
272 operations available for the given python object.</p> |
|
273 <p id="ch2intro_26">Eg 5:</p> |
|
274 <pre class="programlisting"> |
|
275 In [4]: a = 6 |
|
276 |
|
277 In [5]: a. |
|
278 a.__abs__ a.__divmod__ a.__index__ a.__neg__ a.__rand__ a.__rmod__ a.__rxor__ |
|
279 a.__add__ a.__doc__ a.__init__ a.__new__ a.__rdiv__ a.__rmul__ a.__setattr__ |
|
280 a.__and__ a.__float__ a.__int__ a.__nonzero__ a.__rdivmod__ a.__ror__ a.__str__ |
|
281 a.__class__ a.__floordiv__ a.__invert__ a.__oct__ a.__reduce__ a.__rpow__ a.__sub__ |
|
282 a.__cmp__ a.__getattribute__ a.__long__ a.__or__ a.__reduce_ex__ a.__rrshift__ a.__truediv__ |
|
283 a.__coerce__ a.__getnewargs__ a.__lshift__ a.__pos__ a.__repr__ a.__rshift__ a.__xor__ |
|
284 a.__delattr__ a.__hash__ a.__mod__ a.__pow__ a.__rfloordiv__ a.__rsub__ |
|
285 a.__div__ a.__hex__ a.__mul__ a.__radd__ a.__rlshift__ a.__rtruediv__</pre> |
|
286 <p id="ch2intro_27">In this example, we initialized 'a' (a variable - a concept that will be |
|
287 discussed in the subsequent sections.) to 6. In the next line when the <span class="emphasis"><em>tab</em></span> key |
|
288 is pressed after typing '<span class="emphasis"><em>a.</em></span>' ipython displays the set of all possible methods |
|
289 that are applicable on the object 'a' (an integer in this context). Ipython |
|
290 provides many such datatype specific features which will be presented in the |
|
291 further sections as and when the datatypes are introduced.</p> |
|
292 </div> |
|
293 </div> |
|
294 <div class="section" title="3.Editing and running a python file"> |
|
295 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
296 <a name="id2967075"></a>3.Editing and running a python file</h2></div></div></div> |
|
297 <p id="ch2intro_28">The previous sections focused on the use of the interpreter to run python code. |
|
298 While the interpeter is an excellent tool to test simple solutions and |
|
299 experiment with small code snippets, its main disadvantage is that everything |
|
300 written in the interpreter is lost once its quit. Most of the times a program is |
|
301 used by people other than the author. So the programs have to be available in |
|
302 some form suitable for distribution, and hence they are written in files. This |
|
303 section will focus on editing and running python files. Start by opening a text |
|
304 editor ( it is recommended you choose one from the list at the top of this page ). |
|
305 In the editor type down python code and save the file with an extension <span class="strong"><strong>.py</strong></span> |
|
306 (python files have an extension of .py). Once done with the editing, save the |
|
307 file and exit the editor.</p> |
|
308 <p id="ch2intro_29">Let us look at a simple example of calculating the gcd of 2 numbers using Python:</p> |
|
309 <p id="ch2intro_2a"><span class="strong"><strong>Creating the first python script(file)</strong></span></p> |
|
310 <pre class="programlisting"> |
|
311 $ emacs gcd.py |
|
312 def gcd(x,y): |
|
313 if x % y == 0: |
|
314 return y |
|
315 return gcd(y, x%y) |
|
316 |
|
317 print gcd(72, 92)</pre> |
|
318 <p id="ch2intro_2b">To run the script, open the shell prompt, navigate to the directory that |
|
319 contains the python file and run <code class="literal">python <filename.py></code> at the prompt ( in this |
|
320 case filename is gcd.py )</p> |
|
321 <p id="ch2intro_2c"><span class="strong"><strong>Running the python script</strong></span></p> |
|
322 <pre class="programlisting"> |
|
323 $ python gcd.py |
|
324 4 |
|
325 $</pre> |
|
326 <p id="ch2intro_2d">Another method to run a python script would be to include the line</p> |
|
327 <p id="ch2intro_2e"><code class="literal">#! /usr/bin/python</code></p> |
|
328 <p id="ch2intro_2f">at the beginning of the python file and then make the file executable by</p> |
|
329 <p id="ch2intro_30">$ chmod a+x <span class="emphasis"><em>filename.py</em></span></p> |
|
330 <p id="ch2intro_31">Once this is done, the script can be run as a standalone program as follows:</p> |
|
331 <p id="ch2intro_32">$ ./<span class="emphasis"><em>filename.py</em></span></p> |
|
332 </div> |
|
333 <div class="section" title="4.Basic Datatypes and operators in Python"> |
|
334 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
335 <a name="id2967182"></a>4.Basic Datatypes and operators in Python</h2></div></div></div> |
|
336 <p id="ch2intro_33">Python provides the following set of basic datatypes.</p> |
|
337 <div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
338 <li class="listitem" style="list-style-type: *"><p id="ch2intro_34">Numbers: int, float, long, complex</p></li> |
|
339 <li class="listitem" style="list-style-type: *"><p id="ch2intro_35">Strings</p></li> |
|
340 <li class="listitem" style="list-style-type: *"><p id="ch2intro_36">Boolean</p></li> |
|
341 </ul></div> |
|
342 <div class="section" title="4.1.Numbers"> |
|
343 <div class="titlepage"><div><div><h3 class="title"> |
|
344 <a name="id2967216"></a>4.1.Numbers</h3></div></div></div> |
|
345 <p id="ch2intro_37">Numbers were introduced in the examples presented in the interactive interpreter |
|
346 section. Numbers include types as mentioned earlier viz., int (integers), float |
|
347 (floating point numbers), long (large integers), complex (complex numbers with |
|
348 real and imaginary parts). Python is not a strongly typed language, which means |
|
349 the type of a variable need not mentioned during its initialization. Let us look |
|
350 at a few examples.</p> |
|
351 <p id="ch2intro_38">Eg 6:</p> |
|
352 <pre class="programlisting"> |
|
353 >>> a = 1 #here a is an integer variable</pre> |
|
354 <p id="ch2intro_39">Eg 7:</p> |
|
355 <pre class="programlisting"> |
|
356 >>> lng = 122333444455555666666777777788888888999999999 #here lng is a variable of type long |
|
357 >>> lng |
|
358 122333444455555666666777777788888888999999999L #notice the trailing 'L' |
|
359 >>> print lng |
|
360 122333444455555666666777777788888888999999999 #notice the absence of the trailing 'L' |
|
361 >>> lng+1 |
|
362 122333444455555666666777777788888889000000000L</pre> |
|
363 <p id="ch2intro_3a">Long numbers are the same as integers in almost all aspects. They can be used in |
|
364 operations just like integers and along with integers without any distinction. |
|
365 The only distinction comes during type checking (which is not a healthy practice). |
|
366 Long numbers are tucked with a trailing 'L' just to signify that they are long. |
|
367 Notice that in the example just lng at the prompt displays the value of the variable |
|
368 with the 'L' whereas <code class="literal">print lng</code> displays without the 'L'. This is because print |
|
369 formats the output before printing. Also in the example, notice that adding an |
|
370 integer to a long does not give any errors and the result is as expected. So for |
|
371 all practical purposes longs can be treated as ints.</p> |
|
372 <p id="ch2intro_3b">Eg 8:</p> |
|
373 <pre class="programlisting"> |
|
374 >>> fl = 3.14159 #fl is a float variable |
|
375 >>> e = 1.234e-4 #e is also a float variable, specified in the exponential form |
|
376 >>> a = 1 |
|
377 >>> b = 2 |
|
378 >>> a/b #integer division |
|
379 0 |
|
380 >>> a/fl #floating point division |
|
381 0.31831015504887655 |
|
382 >>> e/fl |
|
383 3.9279473133031364e-05</pre> |
|
384 <p id="ch2intro_3c">Floating point numbers, simply called floats are real numbers with a decimal point. |
|
385 The example above shows the initialization of a float variable. Shown also in this |
|
386 example is the difference between integer division and floating point division. |
|
387 'a' and 'b' here are integer variables and hence the division gives 0 as the quotient. |
|
388 When either of the operands is a float, the operation is a floating point division, |
|
389 and the result is also a float as illustrated.</p> |
|
390 <p id="ch2intro_3d">Eg 9:</p> |
|
391 <pre class="programlisting"> |
|
392 >>> cplx = 3 + 4j #cplx is a complex variable |
|
393 >>> cplx |
|
394 (3+4j) |
|
395 >>> print cplx.real #prints the real part of the complex number |
|
396 3.0 |
|
397 >>> print cplx.imag #prints the imaginary part of the complex number |
|
398 4.0 |
|
399 >>> print cplx*fl #multiplies the real and imag parts of the complex number with the multiplier |
|
400 (9.42477+12.56636j) |
|
401 >>> abs(cplx) #returns the absolute value of the complex number |
|
402 5.0</pre> |
|
403 <p id="ch2intro_3e">Python provides a datatype for complex numbers. Complex numbers are initialized |
|
404 as 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 and |
|
405 imaginary parts of the complex number as shown. The <span class="emphasis"><em>abs()</em></span> returns the absolute |
|
406 value of the complex number.</p> |
|
407 </div> |
|
408 <div class="section" title="4.2.Variables"> |
|
409 <div class="titlepage"><div><div><h3 class="title"> |
|
410 <a name="id2967346"></a>4.2.Variables</h3></div></div></div> |
|
411 <p id="ch2intro_3f">Variables are just names that represent a value. Variables have already been |
|
412 introduced in the various examples from the previous sections. Certain rules about |
|
413 using variables:</p> |
|
414 <div class="itemizedlist"><ul class="itemizedlist" type="*"> |
|
415 <li class="listitem" style="list-style-type: *"><p id="ch2intro_40">Variables have to be initialized or assigned a value before being used.</p></li> |
|
416 <li class="listitem" style="list-style-type: *"><p id="ch2intro_41">Variable names can consist of letters, digits and underscores(_).</p></li> |
|
417 <li class="listitem" style="list-style-type: *"><p id="ch2intro_42">Variable names cannot begin with digits, but can contain digits in them.</p></li> |
|
418 </ul></div> |
|
419 <p id="ch2intro_43">In reference to the previous section examples, 'a', 'b', 'lng', 'fl', 'e' and 'cplx' |
|
420 are all variables of various datatypes.</p> |
|
421 <pre class="programlisting"> |
|
422 Note: Python is not a strongly typed language and hence an integer variable can at a |
|
423 later stage be used as a float variable as well.</pre> |
|
424 </div> |
|
425 <div class="section" title="4.3.Strings"> |
|
426 <div class="titlepage"><div><div><h3 class="title"> |
|
427 <a name="id2967394"></a>4.3.Strings</h3></div></div></div> |
|
428 <p id="ch2intro_44">Strings are one of the essential data structures of any programming language. |
|
429 The <code class="literal">print "Hello, World!"</code> program was introduced in the earlier section, and |
|
430 the <span class="emphasis"><em>"Hello, World!"</em></span> in the print statement is a string. A string is basically |
|
431 a set of characters. Strings can be represented in various ways shown below:</p> |
|
432 <pre class="programlisting"> |
|
433 s = 'this is a string' # a string variable can be represented using single quotes |
|
434 s = 'This one has "quotes" inside!' # The string can have quotes inside it as shown |
|
435 s = "I have 'single-quotes' inside!" |
|
436 l = "A string spanning many lines |
|
437 one more line |
|
438 yet another" # a string can span more than a single line. |
|
439 t = """A triple quoted string does # another way of representing multiline strings. |
|
440 not need to be escaped at the end and |
|
441 "can have nested quotes" etc."""</pre> |
|
442 <p id="ch2intro_45">Try the following on the interpreter: |
|
443 <code class="literal">s = 'this is a string with 'quotes' of similar kind'</code></p> |
|
444 <p id="ch2intro_46"><span class="strong"><strong>Exercise: How to use single quotes within single quotes in a string as shown |
|
445 in the above example without getting an error?</strong></span></p> |
|
446 <div class="section" title="4.3.1.String operations"> |
|
447 <div class="titlepage"><div><div><h4 class="title"> |
|
448 <a name="id2967445"></a>4.3.1.String operations</h4></div></div></div> |
|
449 <p id="ch2intro_47">A few basic string operations are presented here.</p> |
|
450 <p id="ch2intro_48"><span class="strong"><strong>String concatenation</strong></span> |
|
451 String concatenation is done by simple addition of two strings.</p> |
|
452 <pre class="programlisting"> |
|
453 >>> x = 'Hello' |
|
454 >>> y = ' Python' |
|
455 >>> print x+y |
|
456 Hello Python</pre> |
|
457 <p id="ch2intro_49"><span class="emphasis"><em>Try this yourself:</em></span></p> |
|
458 <pre class="programlisting"> |
|
459 >>> somenum = 13 |
|
460 >>> print x+somenum</pre> |
|
461 <p id="ch2intro_4a">The problem with the above example is that here a string variable and an integer |
|
462 variable are trying to be concantenated. To obtain the desired result from the |
|
463 above example the str(), repr() and the `` can be used.</p> |
|
464 <p id="ch2intro_4b"><span class="strong"><strong>str()</strong></span> simply converts a value to a string in a reasonable form. |
|
465 <span class="strong"><strong>repr()</strong></span> creates a string that is a representation of the value.</p> |
|
466 <p id="ch2intro_4c">The difference can be seen in the example shown below:</p> |
|
467 <pre class="programlisting"> |
|
468 >>> str(1000000000000000000000000000000000000000000000000L) |
|
469 '1000000000000000000000000000000000000000000000000' |
|
470 >>> repr(1000000000000000000000000000000000000000000000000L) |
|
471 '1000000000000000000000000000000000000000000000000L'</pre> |
|
472 <p id="ch2intro_4d">It can be observed that the 'L' in the long value shown was omitted by str(), |
|
473 whereas repr() converted that into a string too. An alternative way of using |
|
474 repr(value) is <code class="literal">`value`</code>.</p> |
|
475 <p id="ch2intro_4e">A few more examples:</p> |
|
476 <pre class="programlisting"> |
|
477 >>> x = "Let's go nto Pycon" |
|
478 >>> print x |
|
479 Let's go |
|
480 to Pycon</pre> |
|
481 <p id="ch2intro_4f">In the above example, notice that the 'n'(newline) character is formatted and |
|
482 the string is printed on two lines. The strings discussed until now were normal |
|
483 strings. Other than these there are two other types of strings namely, raw strings |
|
484 and unicode strings.</p> |
|
485 <p id="ch2intro_50"><span class="strong"><strong>Raw strings</strong></span> are strings which are unformatted, that is the backslashes() are |
|
486 not parsed and are left as it is in the string. Raw strings are represented with |
|
487 an 'r' at the start of a string. |
|
488 Let us look at an example</p> |
|
489 <pre class="programlisting"> |
|
490 >>> x = r"Let's go nto Pycon" |
|
491 >>> print x |
|
492 Let's go nto Pycon</pre> |
|
493 <p id="ch2intro_51">Note: The 'n' is not being parsed into a new line and is left as it is.</p> |
|
494 <p id="ch2intro_52"><span class="emphasis"><em>Try this yourself:</em></span></p> |
|
495 <pre class="programlisting"> |
|
496 >>> x = r"Let's go to Pycon "</pre> |
|
497 <p id="ch2intro_53"><span class="strong"><strong>Unicode strings</strong></span> are strings where the characters are Unicode characters as |
|
498 opposed to ASCII characters. Unicode strings are represented with a 'u' at the |
|
499 start of the string. |
|
500 Let us look at an example:</p> |
|
501 <pre class="programlisting"> |
|
502 >>> x = u"Let's go to Pycon!" |
|
503 >>> print x |
|
504 Let's go to Pycon!</pre> |
|
505 </div> |
|
506 </div> |
|
507 <div class="section" title="4.4.Boolean"> |
|
508 <div class="titlepage"><div><div><h3 class="title"> |
|
509 <a name="id2967588"></a>4.4.Boolean</h3></div></div></div> |
|
510 <p id="ch2intro_54">Python also provides special Boolean datatype. A boolean variable can assume a |
|
511 value of either <span class="emphasis"><em>True</em></span> or <span class="emphasis"><em>False</em></span> (Note the capitalizations).</p> |
|
512 <p id="ch2intro_55">Let us look at examples:</p> |
|
513 <pre class="programlisting"> |
|
514 >>> t = True |
|
515 >>> f = not t |
|
516 >>> print f |
|
517 False |
|
518 >>> f or t |
|
519 True |
|
520 >>> f and t |
|
521 False</pre> |
|
522 </div> |
|
523 </div> |
|
524 <div class="section" title="5.The while loop"> |
|
525 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
526 <a name="id2967617"></a>5.The <span class="strong"><strong>while</strong></span> loop</h2></div></div></div> |
|
527 <p id="ch2intro_56">The Python <span class="strong"><strong>while</strong></span> loop is similar to the C/C++ while loop. The syntax is as |
|
528 follows:</p> |
|
529 <pre class="programlisting"> |
|
530 statement 0 |
|
531 while condition: |
|
532 statement 1 #while block |
|
533 statement 2 #while block |
|
534 statement 3 #outside the while block.</pre> |
|
535 <p id="ch2intro_57">Let us look at an example:</p> |
|
536 <pre class="programlisting"> |
|
537 >>> x = 1 |
|
538 >>> while x <= 5: |
|
539 ... print x |
|
540 ... x += 1 |
|
541 ... |
|
542 1 |
|
543 2 |
|
544 3 |
|
545 4 |
|
546 5</pre> |
|
547 </div> |
|
548 <div class="section" title="6.The if conditional"> |
|
549 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
550 <a name="id2967654"></a>6.The <span class="strong"><strong>if</strong></span> conditional</h2></div></div></div> |
|
551 <p id="ch2intro_58">The Python <span class="strong"><strong>if</strong></span> block provides the conditional execution of statements. |
|
552 If the condition evaluates as true the block of statements defined under the if |
|
553 block are executed.</p> |
|
554 <p id="ch2intro_59">If the first block is not executed on account of the condition not being satisfied, |
|
555 the set of statements in the <span class="strong"><strong>else</strong></span> block are executed.</p> |
|
556 <p id="ch2intro_5a">The <span class="strong"><strong>elif</strong></span> block provides the functionality of evaluation of multiple conditions |
|
557 as shown in the example.</p> |
|
558 <p id="ch2intro_5b">The syntax is as follows:</p> |
|
559 <pre class="programlisting"> |
|
560 if condition : |
|
561 statement_1 |
|
562 statement_2 |
|
563 |
|
564 elif condition: |
|
565 statement_3 |
|
566 statement_4 |
|
567 else: |
|
568 statement_5 |
|
569 statement_6</pre> |
|
570 <p id="ch2intro_5c">Let us look at an example:</p> |
|
571 <pre class="programlisting"> |
|
572 >>> n = raw_input("Input a number:") |
|
573 >>> if n < 0: |
|
574 print n," is negative" |
|
575 elif n > 0: |
|
576 print n," is positive" |
|
577 else: |
|
578 print n, " is 0"</pre> |
|
579 </div> |
|
580 <div class="section" title="7.raw_input()"> |
|
581 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
582 <a name="id2967723"></a>7.<span class="strong"><strong>raw_input()</strong></span> |
|
583 </h2></div></div></div> |
|
584 <p id="ch2intro_5d">In the previous example we saw the call to the raw_input() subroutine. |
|
585 The <span class="strong"><strong>raw_input()</strong></span> method is used to take user inputs through the console. |
|
586 Unlike <span class="strong"><strong>input()</strong></span> which assumes the data entered by the user as a standard python |
|
587 expression, <span class="strong"><strong>raw_input()</strong></span> treats all the input data as raw data and converts |
|
588 everything into a string. To illustrate this let us look at an example.</p> |
|
589 <pre class="programlisting"> |
|
590 >>> input("Enter a number thats a palindrome:") |
|
591 Enter a number thats a palindrome:121 |
|
592 121 |
|
593 |
|
594 >>> input("Enter your name:") |
|
595 Enter your name:PythonFreak |
|
596 Traceback (most recent call last): |
|
597 File "<stdin>", line 1, in <module> |
|
598 File "<string>", line 1, in <module> |
|
599 NameError: name 'PythonFreak' is not defined</pre> |
|
600 <p id="ch2intro_5e">As shown above the <span class="strong"><strong>input()</strong></span> assumes that the data entered is a valid Python |
|
601 expression. In the first call it prompts for an integer input and when entered |
|
602 it accepts the integer as an integer, whereas in the second call, when the string |
|
603 is entered without the quotes, <span class="strong"><strong>input()</strong></span> assumes that the entered data is a valid |
|
604 Python expression and hence it raises and exception saying PythonFreak is not |
|
605 defined.</p> |
|
606 <pre class="programlisting"> |
|
607 >>> input("Enter your name:") |
|
608 Enter your name:'PythonFreak' |
|
609 'PythonFreak' |
|
610 >>></pre> |
|
611 <p id="ch2intro_5f">Here the name is accepted because its entered as a string (within quotes). But |
|
612 its unreasonable to go on using quotes each time a string is entered. Hence the |
|
613 alternative is to use <span class="strong"><strong>raw_input()</strong></span>.</p> |
|
614 <p id="ch2intro_60">Let us now look at how <span class="strong"><strong>raw_input()</strong></span> operates with an example.</p> |
|
615 <pre class="programlisting"> |
|
616 >>> raw_input("Enter your name:") |
|
617 Enter your name:PythonFreak |
|
618 'PythonFreak'</pre> |
|
619 <p id="ch2intro_61">Observe that the <span class="strong"><strong>raw_input()</strong></span> is converting it into a string all by itself.</p> |
|
620 <pre class="programlisting"> |
|
621 >>> pal = raw_input("Enter a number thats a palindrome:") |
|
622 Enter a number thats a palindrome:121 |
|
623 '121'</pre> |
|
624 <p id="ch2intro_62">Observe that <span class="strong"><strong>raw_input()</strong></span> is converting the integer 121 also to a string as |
|
625 '121'. Let us look at another example:</p> |
|
626 <pre class="programlisting"> |
|
627 >>> pal = raw_input("Enter a number thats a palindrome:") |
|
628 Enter a number thats a palindrome:121 |
|
629 >>> pal + 2 |
|
630 Traceback (most recent call last): |
|
631 File "<stdin>", line 1, in <module> |
|
632 TypeError: cannot concatenate 'str' and 'int' objects |
|
633 >>> pal |
|
634 '121'</pre> |
|
635 <p id="ch2intro_63">Observe here that the variable <span class="emphasis"><em>pal</em></span> is a string and hence integer operations |
|
636 cannot be performed on it. Hence the exception is raised.</p> |
|
637 </div> |
|
638 <div class="section" title="8.int() method"> |
|
639 <div class="titlepage"><div><div><h2 class="title" style="clear: both"> |
|
640 <a name="id2967877"></a>8.<span class="strong"><strong>int()</strong></span> method</h2></div></div></div> |
|
641 <p id="ch2intro_64">Generally for computing purposes, the data used is not strings or raw data but |
|
642 on integers, floats and similar mathematical data structures. The data obtained |
|
643 from <span class="strong"><strong>raw_input()</strong></span> is raw data in the form of strings. In order to obtain integers |
|
644 from strings we use the method <span class="strong"><strong>int()</strong></span>.</p> |
|
645 <p id="ch2intro_65">Let us look at an example.</p> |
|
646 <pre class="programlisting"> |
|
647 >>> intpal = int(pal) |
|
648 >>> intpal |
|
649 121</pre> |
|
650 <p id="ch2intro_66">In the previous example it was observed that <span class="emphasis"><em>pal</em></span> was a string variable. Here |
|
651 using 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> |
|
652 <p id="ch2intro_67"><span class="emphasis"><em>Try This Yourself:</em></span></p> |
|
653 <pre class="programlisting"> |
|
654 >>> stringvar = raw_input("Enter a name:") |
|
655 Enter a name:Guido Van Rossum |
|
656 >>> stringvar |
|
657 'Guido Van Rossum' |
|
658 >>> numvar = int(stringvar)</pre> |
|
659 </div> |
|
660 </div> |
|
661 </div></body> |
|
662 </html> |
|
663 |
|