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