-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.html
More file actions
9311 lines (6956 loc) · 424 KB
/
Copy pathpython.html
File metadata and controls
9311 lines (6956 loc) · 424 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html><html><body><title>Python tutorial</title>
<h1>Python - Tutorial</h1>
<p>Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.</p>
<h1>Audience</h1>
<p>This tutorial is designed for software programmers who need to learn Python programming language from scratch.</p>
<h1>Prerequisites</h1>
<p>You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus.</p>
<h1>Python Offline Mobile App</h1>
<h1>Execute Python Programs</h1>
<p>For most of the examples given in this tutorial you will find <b>Try it</b> option, so just make use of it and enjoy your learning.</p>
<p>Try following example using <b>Try it</b> option available at the top right corner of the below sample code box −</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
print "Hello, Python!"
</pre>
<title>Python Overview</title>
<h1>Python Overview</h1>
<p>Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.</p>
<p><b>Python is Interpreted:</b> Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.</p>
<p><b>Python is Interactive:</b> You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.</p>
<p><b>Python is Object-Oriented:</b> Python supports Object-Oriented style or technique of programming that encapsulates code within objects.</p>
<p><b>Python is a Beginner's Language:</b> Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.</p>
<h2>History of Python</h2>
<p>Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.</p>
<p>Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.</p>
<p>Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).</p>
<p>Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.</p>
<h2>Python Features</h2>
<p>Python's features include:</p>
<p><b>Easy-to-learn:</b> Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.</p>
<p><b>Easy-to-read:</b> Python code is more clearly defined and visible to the eyes.</p>
<p><b>Easy-to-maintain:</b> Python's source code is fairly easy-to-maintain.</p>
<p><b>A broad standard library:</b> Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.</p>
<p><b>Interactive Mode:</b>Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.</p>
<p><b>Portable:</b> Python can run on a wide variety of hardware platforms and has the same interface on all platforms.</p>
<p><b>Extendable:</b> You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.</p>
<p><b>Databases:</b> Python provides interfaces to all major commercial databases.</p>
<p><b>GUI Programming:</b> Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.</p>
<p><b>Scalable:</b> Python provides a better structure and support for large programs than shell scripting.</p>
<p>Apart from the above-mentioned features, Python has a big list of good features, few are listed below:</p>
<p>It supports functional and structured programming methods as well as OOP.</p>
<p>It can be used as a scripting language or can be compiled to byte-code for building large applications.</p>
<p>It provides very high-level dynamic data types and supports dynamic type checking.</p>
<p>IT supports automatic garbage collection.</p>
<p>It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<title>Python Environment Setup</title>
<h1>Python - Environment Setup</h1>
<h2>Local Environment Setup</h2>
<p>Open a terminal window and type "python" to find out if it is already installed and which version is installed.</p>
<h2>Getting Python</h2>
<h2>Installing Python</h2>
<p>Here is a quick overview of installing Python on various platforms −</p>
<h3>Unix and Linux Installation</h3>
<p>Here are the simple steps to install Python on Unix/Linux machine.</p>
<p>Open a Web browser and go to <a href="https://www.python.org/downloads/" target="_blank" rel="nofollow">https://www.python.org/downloads/</a>.</p>
<p>Follow the link to download zipped source code available for Unix/Linux.</p>
<p>Download and extract files.</p>
<p>Editing the <i>Modules/Setup</i> file if you want to customize some options.</p>
<p>run ./configure script</p>
<p>make</p>
<p>make install</p>
<h3>Windows Installation</h3>
<p>Here are the steps to install Python on Windows machine.</p>
<p>Open a Web browser and go to <a href="https://www.python.org/downloads/" target="_blank" rel="nofollow">https://www.python.org/downloads/</a>.</p>
<p>Follow the link for the Windows installer <i>python-XYZ.msi</i> file where XYZ is the version you need to install.</p>
<h3>Macintosh Installation</h3>
<h2>Setting up PATH</h2>
<p>The <b>path</b> variable is named as PATH in Unix or Path in Windows (Unix is casesensitive; Windows is not).</p>
<h2>Setting path at Unix/Linux</h2>
<p>To add the Python directory to the path for a particular session in Unix −</p>
<p><b>In the csh shell</b> − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.</p>
<p><b>In the bash shell (Linux)</b> − type export ATH="$PATH:/usr/local/bin/python" and press Enter.</p>
<p><b>In the sh or ksh shell</b> − type PATH="$PATH:/usr/local/bin/python" and press Enter.</p>
<p><b>Note</b> − /usr/local/bin/python is the path of the Python directory</p>
<h2>Setting path at Windows</h2>
<p>To add the Python directory to the path for a particular session in Windows −</p>
<p><b>At the command prompt</b> − type path %path%;C:\Python and press Enter.</p>
<p><b>Note</b> − C:\Python is the path of the Python directory</p>
<h2>Python Environment Variables</h2>
<p>Here are important environment variables, which can be recognized by Python −</p>
<p><b>PYTHONPATH</b></p>
<p>It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.</p>
<p><b>PYTHONSTARTUP</b></p>
<p><b>PYTHONCASEOK</b></p>
<p>It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.</p>
<p><b>PYTHONHOME</b></p>
<p>It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.</p>
<h2>Running Python</h2>
<p>There are three different ways to start Python −</p>
<h3>Interactive Interpreter</h3>
<p>Enter <b>python</b> the command line.</p>
<p>Start coding right away in the interactive interpreter.</p>
<p>Here is the list of all the available command line options −</p>
<p><b>-d</b></p>
<p>It provides debug output.</p>
<p><b>-O</b></p>
<p>It generates optimized bytecode (resulting in .pyo files).</p>
<p><b>-S</b></p>
<p>Do not run import site to look for Python paths on startup.</p>
<p><b>-v</b></p>
<p>verbose output (detailed trace on import statements).</p>
<p><b>-X</b></p>
<p>disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.</p>
<p><b>-c cmd</b></p>
<p>run Python script sent in as cmd string</p>
<p><b>file</b></p>
<p>run Python script from given file</p>
<h3>Script from the Command-line</h3>
<p><b>Note</b> − Be sure the file permission mode allows execution.</p>
<h3>Integrated Development Environment</h3>
<p><b>Unix</b> − IDLE is the very first Unix IDE for Python.</p>
<p><b>Windows</b> − PythonWin is the first Windows interface for Python and is an IDE with a GUI.</p>
<p><b>Macintosh</b> − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.</p>
<p><b>Note</b> − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="result notranslate">
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
</pre>
<p>Here is the list of all the available command line options −</p>
<table class="table table-bordered">
<tbody>
<tr>
<th>S.No.</th>
<th style="text-align:center;">Option & Description</th>
</tr>
<tr>
<td>1</td>
<td><p><b>-d</b></p>
<p>It provides debug output.</p></td>
</tr>
<tr>
<td>2</td>
<td><p><b>-O</b></p>
<p>It generates optimized bytecode (resulting in .pyo files).</p></td>
</tr>
<tr>
<td>3</td>
<td><p><b>-S</b></p>
<p>Do not run import site to look for Python paths on startup.</p></td>
</tr>
<tr>
<td>4</td>
<td><p><b>-v</b></p>
<p>verbose output (detailed trace on import statements).</p></td>
</tr>
<tr>
<td>5</td>
<td><p><b>-X</b></p>
<p>disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.</p></td>
</tr>
<tr>
<td>6</td>
<td><p><b>-c cmd</b></p>
<p>run Python script sent in as cmd string</p></td>
</tr>
<tr>
<td>7</td>
<td><p><b>file</b></p>
<p>run Python script from given file</p></td>
</tr>
</tbody>
</table>
<h3>Script from the Command-line</h3>
<p>A Python script can be executed at command line by invoking the interpreter on your
application, as in the following −</p>
<pre class="result notranslate">
$python script.py # Unix/Linux
or
python% script.py # Unix/Linux
or
C: >python script.py # Windows/DOS
</pre>
<title>Python Basic Syntax</title>
<h1>Python Basic Syntax</h1>
<p>The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.</p>
<h2>First Python Program</h2>
<p>Let us execute programs in different modes of programming.</p>
<h3>Interactive Mode Programming</h3>
<p>Invoking the interpreter without passing a script file as a parameter brings up the following prompt −</p>
<p>Type the following text at the Python prompt and press the Enter:</p>
<p>If you are running new version of Python, then you would need to use print statement with parenthesis as in <b>print ("Hello, Python!");</b>. However in Python version 2.4.3, this produces the following result:</p>
<h3>Script Mode Programming</h3>
<p>Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.</p>
<p>Let us write a simple Python program in a script. Python files have extension <b>.py</b>. Type the following source code in a test.py file:</p>
<p>We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −</p>
<p>This produces the following result:</p>
<p>Let us try another way to execute a Python script. Here is the modified test.py file −</p>
<p>We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −</p>
<p>This produces the following result −</p>
<h2>Python Identifiers</h2>
<p>A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).</p>
<p>Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, <b>Manpower</b> and <b>manpower</b> are two different identifiers in Python.</p>
<p>Class names start with an uppercase letter. All other identifiers start with a lowercase letter.</p>
<p>Starting an identifier with a single leading underscore indicates that the identifier is private.</p>
<p>Starting an identifier with two leading underscores indicates a strongly private identifier.</p>
<p>If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.</p>
<h2>Reserved Words</h2>
<p>The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.</p>
<h2>Lines and Indentation</h2>
<p>Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.</p>
<p>The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −</p>
<p>However, the following block generates an error −</p>
<p>Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −</p>
<p><b>Note:</b> Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.</p>
<h2>Multi-Line Statements</h2>
<p>Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −</p>
<p>Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −</p>
<h2>Quotation in Python</h2>
<p>Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.</p>
<p>The triple quotes are used to span the string across multiple lines. For example, all the following are legal −</p>
<h2>Comments in Python</h2>
<p>A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.</p>
<p>This produces the following result −</p>
<p>You can type a comment on the same line after a statement or expression −</p>
<p>You can comment multiple lines as follows −</p>
<h2>Using Blank Lines</h2>
<p>A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.</p>
<p>In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.</p>
<h2>Waiting for the User</h2>
<p>The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −</p>
<p>Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.</p>
<h2>Multiple Statements on a Single Line</h2>
<p>The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −</p>
<h2>Multiple Statement Groups as Suites</h2>
<p>A group of individual statements, which make a single code block are called <b>suites</b> in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.</p>
<p>Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −</p>
<h2>Command Line Arguments</h2>
<p>Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h −</p>
<p>You can also program your script in such a way that it should accept various options. <a href="/python/python_command_line_arguments.htm">Command Line Arguments</a> is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate">
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
</pre>
<p>Type the following text at the Python prompt and press the Enter:</p>
<pre class="prettyprint notranslate">
>>> print "Hello, Python!"
</pre>
<p>If you are running new version of Python, then you would need to use print statement with parenthesis as in <b>print ("Hello, Python!");</b>. However in Python version 2.4.3, this produces the following result:</p>
<pre class="prettyprint notranslate">
Hello, Python!
</pre>
<h3>Script Mode Programming</h3>
<p>Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.</p>
<p>Let us write a simple Python program in a script. Python files have extension <b>.py</b>. Type the following source code in a test.py file:</p>
<pre class="prettyprint notranslate tryit">
print "Hello, Python!"
</pre>
<p>We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −</p>
<pre class="prettyprint notranslate">
$ python test.py
</pre>
<p>This produces the following result:</p>
<pre class="result notanslate">
Hello, Python!
</pre>
<p>Let us try another way to execute a Python script. Here is the modified test.py file −</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
print "Hello, Python!"
</pre>
<p>We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −</p>
<pre class="prettyprint notranslate">
$ chmod +x test.py # This is to make file executable
$./test.py
</pre>
<p>This produces the following result −</p>
<pre class="result">
Hello, Python!
</pre>
<h2>Python Identifiers</h2>
<p>A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).</p>
<p>Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, <b>Manpower</b> and <b>manpower</b> are two different identifiers in Python.</p>
<p>Here are naming conventions for Python identifiers −<p>
<ul class="list">
<li><p>Class names start with an uppercase letter. All other identifiers start with a lowercase letter.</p></li>
<li><p>Starting an identifier with a single leading underscore indicates that the identifier is private.</p></li>
<li><p>Starting an identifier with two leading underscores indicates a strongly private identifier.</p></li>
<li><p>If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.</p></li>
</ul>
<h2>Reserved Words</h2>
<p>The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.</p>
<table class="table table-bordered">
<tr><td>and</td><td>exec</td><td>not</td></tr>
<tr><td>assert</td><td>finally</td><td>or</td></tr>
<tr><td>break</td><td>for</td><td>pass</td></tr>
<tr><td>class</td><td>from</td><td>print</td></tr>
<tr><td>continue</td><td>global</td><td>raise</td></tr>
<tr><td>def</td><td>if</td><td>return</td></tr>
<tr><td>del</td><td>import</td><td>try</td></tr>
<tr><td>elif</td><td>in</td><td>while</td></tr>
<tr><td>else</td><td>is</td><td>with </td></tr>
<tr><td>except</td><td>lambda</td><td>yield</td></tr>
</table>
<h2>Lines and Indentation</h2>
<p>Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.</p>
<p>The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −</p>
<pre class="prettyprint notranslate">
if True:
print "True"
else:
print "False"
</pre>
<p>However, the following block generates an error −</p>
<pre class="prettyprint notranslate">
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
</pre>
<p>Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −</p>
<p><b>Note:</b> Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.</p>
<pre class="prettyprint notranslate">
#!/usr/bin/python
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
</pre>
<h2>Multi-Line Statements</h2>
<p>Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −</p>
<pre class="prettyprint notranslate">
total = item_one + \
item_two + \
item_three
</pre>
<p>Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −</p>
<pre class="prettyprint notranslate">
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
</pre>
<h2>Quotation in Python</h2>
<p>Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.</p>
<p>The triple quotes are used to span the string across multiple lines. For example, all the following are legal −</p>
<pre class="prettyprint notranslate">
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
</pre>
<h2>Comments in Python</h2>
<p>A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
</pre>
<p>This produces the following result −</p>
<pre class="prettyprint notranslate">
Hello, Python!
</pre>
<p>You can type a comment on the same line after a statement or expression −</p>
<pre class="prettyprint notranslate">
name = "Madisetti" # This is again comment
</pre>
<p>You can comment multiple lines as follows −</p>
<pre class="prettyprint notranslate">
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
</pre>
<h2>Using Blank Lines</h2>
<p>A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.</p>
<p>In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.</p>
<h2>Waiting for the User</h2>
<p>The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −</p>
<pre class="prettyprint notranslate">
#!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")
</pre>
<p>Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.</p>
<h2>Multiple Statements on a Single Line</h2>
<p>The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −</p>
<pre class="prettyprint notranslate">
import sys; x = 'foo'; sys.stdout.write(x + '\n')
</pre>
<h2>Multiple Statement Groups as Suites</h2>
<p>A group of individual statements, which make a single code block are called <b>suites</b> in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.</p>
<p>Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −</p>
<pre class="prettyprint notranslate">
if expression :
suite
elif expression :
suite
else :
suite
</pre>
<h2>Command Line Arguments</h2>
<p>Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h −</p>
<pre class="prettyprint notranslate">
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
</pre>
<title>Python Variable Types</title>
<h1>Python Variable Types</h1>
<p>Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.</p>
<p>Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.</p>
<h2>Assigning Values to Variables</h2>
<p>Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.</p>
<p>The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −</p>
<p>Here, 100, 1000.0 and "John" are the values assigned to <i>counter</i>, <i>miles</i>, and <i>name</i> variables, respectively. This produces the following result −</p>
<h2>Multiple Assignment</h2>
<p>Python allows you to assign a single value to several variables simultaneously. For example −</p>
<p>Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −</p>
<p>Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.</p>
<h2>Standard Data Types</h2>
<p>The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.</p>
<p>Python has five standard data types −</p>
<p>Numbers</p>
<p>String</p>
<p>List</p>
<p>Tuple</p>
<p>Dictionary</p>
<h2>Python Numbers</h2>
<p>Number data types store numeric values. Number objects are created when you assign a value to them. For example −</p>
<p>You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −</p>
<p>You can delete a single object or multiple objects by using the del statement. For example −</p>
<p>Python supports four different numerical types −</p>
<p>int (signed integers)</p>
<p>long (long integers, they can also be represented in octal and hexadecimal)</p>
<p>float (floating point real values)</p>
<p>complex (complex numbers)</p>
<h3>Examples</h3>
<p>Here are some examples of numbers −</p>
<p>Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.</p>
<p>A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.</p>
<h2>Python Strings</h2>
<p>Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.</p>
<p>The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −</p>
<p>This will produce the following result −</p>
<h2>Python Lists</h2>
<p>Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.</p>
<p>The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −</p>
<p>This produce the following result −</p>
<h2>Python Tuples</h2>
<p>A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.</p>
<p>The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as <b>read-only</b> lists. For example −</p>
<p>This produce the following result −</p>
<p>The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −</p>
<h2>Python Dictionary</h2>
<p>Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.</p>
<p>Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −</p>
<p>This produce the following result −</p>
<p>Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.</p>
<h2>Data Type Conversion</h2>
<p>Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.</p>
<p>There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.</p>
<p>int(x [,base])</p>
<p>Converts x to an integer. base specifies the base if x is a string.</p>
<p>long(x [,base] )</p>
<p>Converts x to a long integer. base specifies the base if x is a string.</p>
<p>float(x)</p>
<p>Converts x to a floating-point number.</p>
<p>complex(real [,imag])</p>
<p>Creates a complex number.</p>
<p>str(x)</p>
<p>Converts object x to a string representation.</p>
<p>repr(x)</p>
<p>Converts object x to an expression string.</p>
<p>eval(str)</p>
<p>Evaluates a string and returns an object.</p>
<p>tuple(s)</p>
<p>Converts s to a tuple.</p>
<p>list(s)</p>
<p>Converts s to a list.</p>
<p>set(s)</p>
<p>Converts s to a set.</p>
<p>dict(d)</p>
<p>Creates a dictionary. d must be a sequence of (key,value) tuples.</p>
<p>frozenset(s)</p>
<p>Converts s to a frozen set.</p>
<p>chr(x)</p>
<p>Converts an integer to a character.</p>
<p>unichr(x)</p>
<p>Converts an integer to a Unicode character.</p>
<p>ord(x)</p>
<p>Converts a single character to its integer value.</p>
<p>hex(x)</p>
<p>Converts an integer to a hexadecimal string.</p>
<p>oct(x)</p>
<p>Converts an integer to an octal string.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
</pre>
<p>Here, 100, 1000.0 and "John" are the values assigned to <i>counter</i>, <i>miles</i>, and <i>name</i> variables, respectively. This produces the following result −</p>
<pre class="prettyprint notranslate">
100
1000.0
John
</pre>
<h2>Multiple Assignment</h2>
<p>Python allows you to assign a single value to several variables simultaneously. For example −</p>
<pre class="prettyprint notranslate">
a = b = c = 1
</pre>
<p>Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −</p>
<pre class="prettyprint notranslate">
a,b,c = 1,2,"john"
</pre>
<p>Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c.</p>
<h2>Standard Data Types</h2>
<p>The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.</p>
<p>Python has five standard data types −</p>
<ul class="list">
<li><p>Numbers</p></li>
<li><p>String</p></li>
<li><p>List</p></li>
<li><p>Tuple</p></li>
<li><p>Dictionary</p></li>
</ul>
<h2>Python Numbers</h2>
<p>Number data types store numeric values. Number objects are created when you assign a value to them. For example −</p>
<pre class="prettyprint notranslate">
var1 = 1
var2 = 10
</pre>
<p>You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −</p>
<pre class="prettyprint notranslate">
del var1[,var2[,var3[....,varN]]]]
</pre>
<p>You can delete a single object or multiple objects by using the del statement. For example −</p>
<pre class="prettyprint notranslate">
del var
del var_a, var_b
</pre>
<p>Python supports four different numerical types −</p>
<ul class="list">
<li><p>int (signed integers)</p></li>
<li><p>long (long integers, they can also be represented in octal and hexadecimal)</p></li>
<li><p>float (floating point real values)</p></li>
<li><p>complex (complex numbers)</p></li>
</ul>
<h3>Examples</h3>
<p>Here are some examples of numbers −</p>
<table class="table table-bordered">
<tr><th>int</th><th>long</th><th>float</th><th>complex</th></tr>
<tr><td>10</td><td>51924361L</td><td>0.0</td><td>3.14j</td></tr>
<tr><td>100</td><td>-0x19323L</td><td>15.20</td><td>45.j</td></tr>
<tr><td>-786</td><td>0122L</td><td>-21.9</td><td>9.322e-36j</td></tr>
<tr><td>080</td><td>0xDEFABCECBDAECBFBAEl</td><td>32.3+e18</td><td>.876j</td></tr>
<tr><td>-0490</td><td>535633629843L</td><td>-90.</td><td>-.6545+0J</td></tr>
<tr><td>-0x260</td><td>-052318172735L</td><td>-32.54e100</td><td>3e+26J</td></tr>
<tr><td>0x69</td><td>-4721885298529L</td><td>70.2-E12</td><td>4.53e-7j</td></tr>
</table>
<ul class="list">
<li><p>Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.</p></li>
<li><p>A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.</p></li>
</ul>
<h2>Python Strings</h2>
<p>Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.</p>
<p>The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
</pre>
<p>This will produce the following result −</p>
<pre class="result notranslate">
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
</pre>
<h2>Python Lists</h2>
<p>Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.</p>
<p>The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
</pre>
<p>This produce the following result −</p>
<pre class="result notranslate">
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
</pre>
<h2>Python Tuples</h2>
<p>A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.</p>
<p>The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as <b>read-only</b> lists. For example −</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
</pre>
<p>This produce the following result −</p>
<pre class="result notranslate">
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
</pre>
<p>The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −</p>
<pre class="prettyprint notranslate">
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
</pre>
<h2>Python Dictionary</h2>
<p>Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.</p>
<p>Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −</p>
<pre class="prettyprint notranslate tryit">
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
</pre>
<p>This produce the following result −</p>
<pre class="result notranslate">
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
</pre>
<title>Python Basic Operators</title>
<h1>Python Basic Operators</h1>
<p>Operators are the constructs which can manipulate the value of operands.</p>
<p>Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.</p>
<h2>Types of Operator</h2>
<p>Python language supports the following types of operators.</p>
<p>Arithmetic Operators</p>