-
Notifications
You must be signed in to change notification settings - Fork 5
/
main_book.tex
1150 lines (1059 loc) · 40.5 KB
/
main_book.tex
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
\documentclass[letterpaper,12pt]{book}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{geometry}
\renewcommand{\familydefault}{Ubuntu}
\lstset{%
basicstyle=\ttfamily,
language=[LaTeX]{TeX},
}
\usepackage{listings}
\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=Python,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{red},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{black},
breaklines=true,
breakatwhitespace=true,
tabsize=4
}
\usepackage{hyperref}
\hypersetup{
colorlinks,
citecolor=blue,
filecolor=black,
linkcolor=blue,
urlcolor=black}
\usepackage{marginnote}
\usepackage[bottom]{footmisc}
\begin{document}
\tableofcontents
\part{Introduction to Python3}
\chapter{Getting started with Python3}
\section{Python3 Interpretor}
If you are new to Python then we will suggest you should start with any Linux OS, it will give you more scope to design the program and other tools. In this tutorial I'm using Fedora Linux to teach you how to start with \texttt{Python3}. Basically Python language is developed in C language. Python is one of the easy language to learn and you can start with it easily.
Let's get started with Python3 interpretor. You need to type \texttt{python3} in to your interpreter and you are here.
\begin{lstlisting}
$ python3
Python 3.7.0 (default, Sep 10 2018, 16:52:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
\end{lstlisting}
\subsection{Operators}
As I mentioned, Python is interpreted language, you will give input to it and it will give you output instantly.
You can start with additions of numbers.
\begin{lstlisting}
>>> 10 + 20
30
>>> 30 - 10
20
>>> 10 * 2
20
>>> 10 / 2
5.0
>>> 10 // 2
5
>>> 10 % 2
0
>>>
\end{lstlisting}
In above example you could see that as soon as the input is given, Python interpreter is giving output.
\paragraph{}
In Python // operator have special meaning. It will return you the absolute result, while / operator will return result in the float.
\subsection{Relational Operators}
In python you can directly compare two numbers, Python interpreter provide functionality to compare two numbers which most of the language do not provide.
For more clarification see the following examples:
\begin{lstlisting}
>>> 10 == 10
True
>>> 10 > 10
False
>>> 10 < 10
False
>>> 10 <= 10
True
>>> 10 >= 10
True
>>> 10 != 10
False
\end{lstlisting}
\subsection{Bitwise Operators}
Bitwise operators are used to perform bit operations on the numbers. Those numbers are treated as string of bits written in twos complement binary.
\begin{itemize}
\item 0 is written as "0"
\item 1 is written as "1"
\item 2 is written as "10"
\item 3 is "11"
\item .
\item .
\item 1029 is ``10000000101" == 2**10 + 2**2 + 2**0 == 1024 + 4 + 1
\end{itemize}
\subsubsection{Operators}
\begin{itemize}
\item $x \ll y$ : $x$ operator is shifted to left by $y$ bits and it return result of $x$ with shifted $y$ bits. It is same as $x * 2 ** y$
\begin{lstlisting}
>>> 3<<2
12
>>> 3*2**2
12
\end{lstlisting}
\item $x \gg y$ : $x$ operator is shifted to right by $y$ bits and it return result of $x$ with shifted $y$ bits. It is same as $x // 2 ** y$.
\begin{lstlisting}
>>> 8>>2
2
>>> 8//2**2
2
\end{lstlisting}
\item $x \& y $: Bitwise AND, each bit of output is 1 if corresponding bit of $x$ AND $y$ is 1, otherwise it is 0
\begin{lstlisting}
>>> 8 & 8
8
>>> 8 & 2
0
\end{lstlisting}
\item $x | y$ : Bitwise OR, each bit of output is 1 if corresponding bit of $x$ AND $y$ is 1, otherwise it is 0
\begin{lstlisting}
>>> 2 | 2
2
>>> 2 | 4
6
>>>
\end{lstlisting}
\item $\sim x $: Complement, It will gives complement of $x$, the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
\begin{lstlisting}
>>> ~2
-3
\end{lstlisting}
\item $x \wedge y$ : Does a ``bitwise exclusive or". Each bit of the output is the same as the corresponding bit in $x$ if that bit in $y$ is 0, and it's the complement of the bit in $x$ if that bit in $y$ is 1.
\begin{lstlisting}
>>> 1^1
0
>>> 1^2
3
\end{lstlisting}
\end{itemize}
\subsection{Keywords}
In any programming language keywords are present, those are nothing but reserve words. You can not use those words for any variable assignment or for function deceleration.
List of keywords present in the Python\\
\begin{center}
\begin{tabular}{llll}
class & False & None & True \\
and & as & assert & break \\
continue & def & del & elif \\
else & expect & finally & for \\
from & global & if & import \\
in & is & lambda & not \\
or & pass & raise & return \\
try & while & with & yield
\end{tabular}
\end{center}
\section{Variables and assignment}
Python is dynamically typed language, it means it will decide what to do with your input at the run time.
Variable declaration and definition in python is something different. If you want to define integer in other languages, for that you follow this syntax \texttt{<data\textunderscore type> <variable\textunderscore name> = <value>}
In python you can directly assign value to the variable without specifying it's data type. Once you assign value to it Python interpreter will automatically parse it.
It's general syntax is: $<$variable1$>$...$<$variablen$>$ = $<$value1$>$...$<$valuen$>$
\begin{lstlisting}
>>> a = 10
>>> type(a)
<class `int'>
\end{lstlisting}
In above example you assigned \texttt{a = 10} and \texttt{type()} function shows it belongs to the \texttt{class int}.
Now let's assign \texttt{a = ``Hello''} and check it's type.
\begin{lstlisting}
>>> a = "Hello"
>>> type(a)
<class `str'>
\end{lstlisting}
In above example you could see that you can assign different value to same variable and interpreter accepted it.
\subsection{Indentation}
In python body of the statement is not defined by the curly brackets, you have to define body using indentations i.e. spaces.
If you are writing any statement, consider, if statement once you write if statement then you need to specify colon (:), then on the next line specify the spaces to define it's body.
\begin{lstlisting}
if ch == 1:
print("You selected 1st choice")
\end{lstlisting}
For spaces you can either type 4 spaces or you can use tab. \\
NOTE: Mixture of both space and tabs will throw an exception.
\section{Conditional statements}
\subsection{If statement}
If statement is conditional statement. It is used to check the condition between two variables.
Any non zero value is considered as a True value. In python it's syntax is little bit different.
True keyword is used to represent boolean value. In first statement condition is true so it will print the if block. In second statement $ 10 > 10 $ condition is false, it will not print ``True statement".
\begin{lstlisting}
>>> if True:
... print("True statement")
...
True statement
>>> if 10>10:
... print("True statement")
...
>>>
\end{lstlisting}
\subsection{if..else statement}
Like I mentioned in the above statement if is the conditional statement, in if statement if the condition is true, then it will execute the if block or it will skip it.
Here if condition is false then, else block got executed.
\begin{lstlisting}
>>> if False:
... print("If block is printed")
... else:
... print("Else block is printed")
...
Else block is printed
>>>
\end{lstlisting}
\subsection{if..elif statement}
In the python switch statement is not present. If you want to check any choice which is matches to the multiple statement then you need to use elif statement.
elif statement is check the condition, if the condition is true then it will execute the block or else block.
You can write as many elif statement as you want. But remember if one elif statement is executed it will not execute the remaining statement.
\begin{lstlisting}
>>> no = 10
>>> if no > 100:
... print("no is grater")
... elif no < 10:
... print("No is < 10")
... elif no == 10:
... print("No is equal to 10")
... elif no == 10:
... print("No is 10")
... else:
... print("Unknown value of no")
...
No is equal to 10
\end{lstlisting}
In above statement you can see that once the condition is true it skip the all the next elif statements.
\section{Loops}
In Python there are two main loops:
\begin{enumerate}
\item For loop
\item While loop
\end{enumerate}
\subsection{For loop}
For loop is basic loop. It is designed in such a way that it can iterate on the multiple objects.
Consider the following example:
\begin{lstlisting}
>>> for i in range(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
>>>
\end{lstlisting}
In above example range is the inbuilt function which will return the list of the integer numbers from 0 to 9.
For loop by default pointing to zero location and printing the value.
In for loop values are auto increment.
\subsection{While loop}
While loop is used where for loop have limitations. One thing about the for loop it is basically used for iterating the objects. While loop is used to perform some mathematical operations or to perform some operations on user defined inputs etc.
\begin{lstlisting}
>>> i = 0
>>> while i < 10:
... print(i)
... i = i + 1
...
0
1
2
3
4
5
6
7
8
9
>>>
\end{lstlisting}
\subsection{Continue statement}
Continue statement is used to transfer the program execution back to the loop.
\begin{lstlisting}
>>> i = 0
>>> while i < 10:
... i = i + 1
... if i == 5:
... continue
... print(i)
...
1
2
3
4
6
7
8
9
10
>>>
\end{lstlisting}
In above example the control statement is forwarded to while loop again when condition is true. In output you can observe that it is not printed 5.
\subsection{Break statement}
Break statement is used to exit the loop. It's uses is same as continue statement.
\begin{lstlisting}
>>> i = 0
>>> while i < 10:
... i = i + 1
... if i == 5:
... break
... print(i)
...
1
2
3
4
>>>
\end{lstlisting}
\section{Strings}
In Python strings are defined using either ` quotes or `` quotes, but all of them treated as equally. When write a string it is a object of class \texttt{str}.
\begin{lstlisting}
>>> `hello' == "hello"
True
>>> type(`hello')
<class `str'>
\end{lstlisting}
If you specify \textbf{hello} without quotes then python interpreter will treat it as variable. If interpreter will find any variable then it will work otherwise it will throw an error.
\begin{lstlisting}
>>> hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined
\end{lstlisting}
\subsubsection{String Methods}
You can check properties of string using \texttt{dir()} method.
\begin{lstlisting}
>>> dir('hello')
['__add__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__',
'__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', `zfill']
\end{lstlisting}
You can use the string properties using \texttt{.} symbol.
\begin{lstlisting}
>>> s = `Hello'
>>> s.upper()
HELLO
\end{lstlisting}
\subsection{Operation on strings}
\subsubsection{String Concatenation}
You can concat two string using \texttt{+} operator.
\begin{lstlisting}
>>> h = "Hello "
>>> i = "World"
>>> h + i
'Hello World'
\end{lstlisting}
\subsubsection{String Multiplication}
You can not subtract or divide string in Python. But you can multiply the strings with Python. When you multiply with the number it will create that strings references.
\begin{lstlisting}
>>> "Hello" * 5
`HelloHelloHelloHelloHello'
\end{lstlisting}
If you can multiply to the string with the numbers then it is easy to print star pattern in Python.
\begin{lstlisting}
>>> for i in range(1, 6):
... print(`*' * i)
...
*
**
***
****
*****
\end{lstlisting}
\subsubsection{Substring in String}
To check substring is present in the string is too much easy in the Python. You can use \texttt{in} keyword to check the substring is present or not.
\begin{lstlisting}
>>> s = "Incredible India!!"
>>> "India" in s
True
>>> "!!" in s
True
>>> "#" in s
False
>>>
\end{lstlisting}
\subsection{Iteration on string}
You can iterate on the string using for loop. For loop automatically stops when string ended, you do not need to provide length of the string.
\begin{lstlisting}
>>> for i in 'hello':
... print(i)
...
h
e
l
l
o
\end{lstlisting}
\subsection{String Slicing}
It will be more useful if strings are able to access using Python's array like syntax. Here in Python indexing is always starts with zero.\\
In python you can use -1, -2.. and so on to access the characters in the string, it will start accessing it from end of the string.
\begin{lstlisting}
>>> s = "Hello"
>>> s[0]
'H'
>>> s[-1]
'o'
\end{lstlisting}
Python will give you more easy syntax to access the string. In python you can access the strings with the following syntax.
\begin{lstlisting}
[start:stop:jump]
\end{lstlisting}
Start is from where you want to start accessing the string.\\
Stop is to where you want to stop accessing the string.\\
Jump is for jumping on the string.\\
Let's see few examples:
\begin{lstlisting}
>>> s[2:] # It will print all the string from 2.
'llo'
>>> s[2:3] # It will print string between index 2 to 3.
'l'
>>> s[:3] # It will print the string till 3.
'Hel'
>>> s[::2] # It will jump on the string.
'Hlo'
>>> s[-1:] # It will print the string starting with o char.
'o'
>>> s[:-1] # It will print the string expect last char.
'Hell'
>>> s[::-1] # It will reverse the string
'olleH'
\end{lstlisting}
\section{Lists}
Lists are the basic data structure in the Python. Lists are nothing but the array but they do not have fixed size, and they are heterogeneous. Lists can accept different type of elements.
You can define the lists using following ways:
\begin{lstlisting}
>>> l = []
>>> l1 = list()
\end{lstlisting}
Above statements will create the empty lists. Here \texttt{list} is the inbuilt method used for creating the list instance.
Again using \texttt{dir()} method you can check the properties of the lists.
If you want to add the element in to the empty list then you can use \textsc{append} method to add element in to list.
\begin{lstlisting}
>>> l.append(10)
>>> l
[10]
\end{lstlisting}
\subsection{List methods}
\begin{itemize}
\item append(): To append element to the list.
\item clear(): To clear the list.
\item copy(): To copy the list in to the another variable. \footnote{ If we can directly copy one variable using assignment operator then why we need `copy' method?\\ Basically in python when assignment (=) operator, that time new variable just simply point to the list location.
\\
So if you change the list using old variable then new variable will reflect the change. But if you create new variable using copy(), then your new variable did not get affected.\\
}
\item count(): Count the element occurrences in the list.
\item extend(): To extend the existing list with another list. You can pass any object (string, list, dict, set) it will extend it to the list.
\item index(): It will return index of the element.
\item insert(): To insert the element at specific location. This method accepts two parameters, 1st one is index and 2nd is value.
\item pop(): To pop the element from the list. By default it will remove the elements from the end of the list. If you want to remove the elements from any location then you can pass index at it.
\item remove(): To remove the element from the list.
\item reverse(): To reverse the list.
\item sort(): To sort the elements in the list.
\end{itemize}
\clearpage
\subsection{Operation On Lists}
On lists you can perform different operations. You can add two lists. Ex:
\begin{lstlisting}
>>> l = [1, 2, 3]
>>> l1 = [4, 5, 6]
>>> l + l1
[1, 2, 3, 4, 5, 6]
\end{lstlisting}
You can multiply to list by number. It will create it's references but not the actual list.
\begin{lstlisting}
>>> [1] * 3
[1, 1, 1]
\end{lstlisting}
Elements in the lists can be checked using \texttt{in} keywords. It is same as checking the substring in string.
\begin{lstlisting}
>>> 1 in l
True
>>> 10 in l
False
\end{lstlisting}
\subsection{Iteration on Lists}
You can iterate on the list with for loop and using while loop.
\begin{lstlisting}
>>> l = [1, 2, 3]
>>> for i in l:
... print(i)
...
1
2
3
>>> i = 0
>>> while i < len(l):
... print(l[i])
... i += 1
...
1
2
3
>>>
\end{lstlisting}
\subsection{List Slicing}
List slicing is same as string slicing. See the following few examples.
\begin{lstlisting}
>>> l
[1, 2, 3]
>>> l[0]
1
>>> l[:1]
[1]
>>> l[:2]
[1, 2]
>>> l[0:2]
[1, 2]
>>> l[0::2]
[1]
>>> l[::-1]
[3, 2, 1]
>>>
\end{lstlisting}
\section{Tuples}
Tuples are same like lists. It is represent using round bracket $'('$ and $')'$.\\
Tuples are immutable objects, those can not be modified.
You can not update the value in the Tuple.
You can not add or remove the elements in the Tuple.
\begin{lstlisting}
>>> t = tuple()
>>> t
()
>>> t = (10, 20, 30)
>>> t
(10, 20, 30)
>>>
\end{lstlisting}
\subsubsection{Tuple methods}
You can check the properties of the Tuples using \textbf{dir} method. You will find only two properties.
\begin{itemize}
\item count(): It will give you the count of the elements in the tuple.
\item index(): It will give you the index of the element.
\end{itemize}
\subsubsection{Operations on Tuples}
As we saw in the lists, you can add two Tuples. Ex:
\begin{lstlisting}
>>> t
(10, 20, 30)
>>> t + t
(10, 20, 30, 10, 20, 30)
>>>
\end{lstlisting}
You can multiply the Tuple by number. It will create it's references, but not the actual list.
\begin{lstlisting}
>>> t * 3
(10, 20, 30, 10, 20, 30, 10, 20, 30)
\end{lstlisting}
\subsubsection{Iteration on Tuples}
You can iterate on the list using for loop and while loop.
\begin{lstlisting}
>>> for i in t:
... print(i)
...
10
20
30
>>> i = 0
>>> while i < len(t):
... print(t[i])
... i += 1
...
10
20
30
>>>
\end{lstlisting}
\subsubsection{Tuple Slicing}
You can perform slicing operations on the lists. See following few examples:
\begin{lstlisting}
>>> t[0]
10
>>> t[:2]
(10, 20)
>>> t[2:5]
(30, 40, 50)
>>> t[4:]
(50, 60, 70)
>>> t[4::-1]
(50, 40, 30, 20, 10)
>>> t[::2]
(10, 30, 50, 70)
>>>
\end{lstlisting}
\section{Dictionaries}
Dictionaries are based on the hash tables data structure in C. Dictionaries are defined using key and value. You can use curly braces ${}$ to define the dictionaries.
Dictionaries are based on key and values. For each value there is one key associated with it.
\begin{lstlisting}
>>> d = {}
>>> d = {'country': 'India',
... 'capital': 'Delhi',
... 'states': 29}
>>> d
{'country': 'India', 'capital': 'Delhi', 'states': 29}
\end{lstlisting}
You can access the values using associated keys, and you can replace it using simple way.
\begin{lstlisting}
>>> d['states']
29
>>> d['states'] = 30
>>> d
{'country': 'India', 'capital': 'Delhi', 'states': 30}
>>> d['Languages'] = ['Hindi', 'English', 'Tamil', 'Malyalum',
'Marathi', 'Gujarati']
\end{lstlisting}
Keys in the dictionary are anything those can be string, integer, floating point values or any module object.
\begin{lstlisting}
>>> import os
>>> d = {}
>>> d[os] = 'os'
>>> d[1] = 'One'
>>> d['two'] = 2
>>> d[3.3] = 'three.three'
>>> d
{<module 'os' from '/usr/lib64/python3.6/os.py'>: 'os', 1: 'One', 'two': 2, 3.3: 'three.three'}
\end{lstlisting}
\subsection{Dictionary Methods}
Dictionary have following methods:
\begin{itemize}
\item clear() : To clear the dictionary.
\item copy() : To copy the dictionary to the another variable.
\item get() : Get is used for getting the value of the specific key in the dictionary or it will return \texttt{None}.
\item items() : This method will return the all the items in the dictionary inside the list. This list will consist the pair of the key and value tuple.
\item keys() : This method will return all the keys inside the dict.
\item pop() : This method will pop specified key and return the value.
\item popitem(): This method will pop any random key and value from they dictionary, it will return the tuple of key and value.
\item update(): This method will update the dictionary with new values or old keys with new values.
\item values() : This method will return the list of the all values.
\item fromkeys() : This method will return the new dictionary with keys from iterable and values equal to values.
\end{itemize}
\subsection{Iteration on Dictionary}
You can iterate on the dictionary using the for loop. By default it will iterate on the keys.
\begin{lstlisting}
>>> d = {'one' : 1, 'two': 2, 'three': 3}
>>> for i in d:
... print(i)
...
one
two
three
>>>
\end{lstlisting}
In the dictionary you can iterate only values. For that you need to use \texttt{values()} method.
\begin{lstlisting}
>>> for i in d.values():
... print(i)
...
1
2
3
>>>
\end{lstlisting}
Using the beauty of the for loop you can iterate on the key and value at the same time. For that you can use \texttt{items()} method.
\begin{lstlisting}
>>> for i, j in d.items():
... print(i, j)
...
one 1
two 2
three 3
>>>
\end{lstlisting}
\section{Functions}
Function is a block of statements which will perform single action. Function will provide modular code, which will be more easy to read. You can reuse this code to perform some action which will save your time.
In Python you can define the function using the \texttt{def} keyword.
After the def keyword you define the name of the function and later in the parenthesis you provide the arguments, after the arguments line ends with the \texttt{$:$} which indicate that from the next line body of the function will be begin.
\begin{lstlisting}
>>> def add():
... print("Addition : ", 10 + 20)
...
>>> add()
Addition : 30
\end{lstlisting}
Above code will show the simple example of the function. This add function will print the addition of the two numbers. You can call any function using \texttt{function\textunderscore name$($args$)$} syntax, for Ex. \texttt{add()} in above code.
In Python you can return the values from the function using \texttt{return} keyword. Below code shows some example of the function with with return values.
\begin{lstlisting}
>>> def add():
... return 10+20
...
>>> add()
30
>>> t = add()
>>> t
30
>>> def add():
... return 10+20
...
>>> def sub():
... print(20 - 10)
...
>>>
>>> u = sub()
10
>>> print(u)
None
>>>
\end{lstlisting}
In above example add function will return the value, which is addition of the two numbers. You can store that value in a variable for later use.
\paragraph{}
Let's see other side, what if function do not return any value? In that case it will return \texttt{None} keyword. You can see the example in above code with function sub. Function will print the subtraction but it will not return anything. By default the value is \texttt{None}.
\subsection{Functions with arguments}
In functions arguments can be passed, In function you can pass $n$ no of arguments. To pass the arguments in the function you do not need to specify the data type, which we specify in C, C++ or Java. As mentioned earlier, Python is dynamic language.
\begin{lstlisting}
>>> def add(a, b):
... return a + b
...
>>> add(109, 23)
132
>>> add("abc", "def")
'abcdef'
>>> add([1], [2])
[1, 2]
>>> add(109)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'b'
>>> add()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() missing 2 required positional arguments: 'a' and 'b'
\end{lstlisting}
In above program, two arguments are passed (a and b) to the function, and it is not defined with the data types. That means you can pass anything in the function call. You can pass integer or you can pass list or you can pass list.
\paragraph{}
If you are not passing expected arguments to the function then function will throw an error.
\subsection{*args and **kwargs in Function}
*args and **kwargs are play major role in function arguments. Consider if you want to pass $n$ no of arguments in to the function, some languages have restrictions on that, you can pass the arguments which are defined in the function. But Python gives you more scope to pass the $n$ no of arguments to the function.
\begin{itemize}
\item **args used for the passing $n$ no of positional arguments tot the function.
\begin{lstlisting}
>>> def add(*args):
... return sum(args)
...
>>>
>>> add(10, 20, 30, 40, 50, 60)
210
>>>
\end{lstlisting}
*args accept all the arguments in to the tuple.
\item **kwargs used for the passing $n$ no of key and value based arguments to the function.
\begin{lstlisting}
>>> def details(**kwargs):
... print(kwargs)
...
>>>
>>> details(name='John',surname='Doe',age=10,height=5.5)
{'name': 'John', 'surname': 'Doe', 'age': 10, 'height': 5.5}
\end{lstlisting}
**kwargs accepts all the arguments in to the dictionary.
\end{itemize}
\section{Decorators}
Decorators are the functions, which take function as input argument. You can decorate any functions with decorators and change the functionality of the function.
\paragraph{}
To understand the Decorators in deep, let's revisit functions once more. Now you know that how to define function and how to call it. But what if you didn't call it and just wrote the name?
\begin{lstlisting}
>>> def add(a, b):
... return a + b
...
>>> add
<function add at 0x7f566467d0d0>
\end{lstlisting}
Yes.. it will show you address of that function. It is telling you that function is present at some location on memory. If you will get address of that function then you can play around it.
\paragraph{}
Remember we did not called the function yet, we just print it's memory location. If that is the case then we can pass this function as an argument to another function (like call by reference in C).
\begin{lstlisting}
>>> def wrapper(func):
... print("Before func")
... print(func(10, 20))
... print("After func")
...
>>> wrapper(add)
Before func
30
After func
>>>
\end{lstlisting}
In above example, I wrote another function name as 'wrapper' and passed one argument 'add' in it, and inside the wrapper function I called function 'func' with two parameters.
After hitting enter, we could see that function add print addition 30 in between 'Before func' and 'After func'.
\paragraph{}
So basically this happened, I passed 'add' to 'wrapper' and when wrapper get called it printed "Before func" then it will call 'add' function which takes two arguments and return and print the result, After that it will print "After func". So this passed add function is get called within the 'wrapper' function.
\paragraph{}
Python allows us to decorate the functions using decorator, so we can write the code like this
\begin{lstlisting}
>>> def wrapper(func):
... print("Before func")
... func()
... print("After func")
...
>>> @wrapper
... def hello_world():
... print("Hello World")
...
Before func
Hello World
After func
>>>
\end{lstlisting}
When you decorate any function, by default python interpreter call wrapper function add pass "hello\textunderscore world" function reference in to it.
\paragraph{}
Basically we can write above decorator function in simple form
\begin{lstlisting}
>>> def wrapper(func):
... print("Before func")
... func()
... print("After func")
...
>>> @wrapper
... def hello_world():
... print("Hello World")
...
Before func
Hello World
After func
\end{lstlisting}
Okay.. now I expect you got some understanding of the decorators. You might have notice that it get called automatically by the interpreter.
\section{Exception Handling}
In Python there are multiple built in exceptions are present. Exceptions are designed to handle the error in running program. Consider if you are converting the strings to the integer, which is against the Python programming language rule. To handle this situation exceptions are used. If exceptions are not used then program will crash.
\paragraph{}
In Python exceptions are defined using \texttt{try},\texttt{except}, \texttt{finally} and \texttt{else} keywords. In the \texttt{try} block you can write your code, if you know that this will cause an error then you can write that in to the \texttt{try} block. To handle the error you can write your error message in to the \texttt{except} block.
\paragraph{}
Once error occur in \texttt{try} block then control passes to the \texttt{except} block and continues the program execution.
\begin{lstlisting}
try:
int("abc")
except:
print("Error occured")
print("Hello")
\end{lstlisting}
Let's consider the another example, If you want use should insert proper integer value then you should write it using following way. This program will run until user will not provide the integer value.
\begin{lstlisting}
while True:
val = input("Enter Value: ")
try:
int(val)
break
except:
print("Invalid value inserted.")
continue
print("Hello")
$ python3 /tmp/exception.py
Enter Value: abc
Invalid value inserted.
Enter Value: 123sad
Invalid value inserted.
Enter Value: 123
Hello
\end{lstlisting}
In Python multiple exceptions are present, those exception are used with specific conditions, You will use \texttt{ValueError} exception when convert the string value to integer.
\begin{lstlisting}
d = {1:'abc'}
while True:
val = input("Enter Value: ")
try:
int(val)
d[int(val)]
break
except ValueError:
print("Invalid value inserted.")
except KeyError:
print("Key is not available in dict")
print("Hello")
\end{lstlisting}
In above program if you provide another value expect digits then you will get value error. If you provide the any digit except 1 then it will throw an key error.
Exception is generic class, if you don't know which error will occur then you will write Exception class and print it.
\begin{lstlisting}
d = {1:'abc'}
while True:
val = input("Enter Value: ")
try:
int(val)
d[int(val)]
break
except Exception as e:
print(e)
print("Error occured")
print("Hello")
\end{lstlisting}
\section{Class}
Class is nothing but the group of the methods and variables. Classes are the basic building block of Object Oriented programming.
\paragraph{}
In Python you can define the classes using $class$ keyword. Inside the class you can define the methods which are class methods. To define the methods are related to the class, first argument passed is $self$, it tells the compiler this method is class method. That means you can not access this method without creating it's object.
\begin{lstlisting}
>>> class math_op():
... def get_add(self, a, b):
... return a + b
...
>>>
\end{lstlisting}
\subsection{Objects}
Objects are the instance of the class. You can create the object of the class with giving the class reference. Once you created the object you can access class methods using $(.)$.
\begin{lstlisting}
>>> m = math_op()
>>> m.get_add(10, 20)
30
>>>