-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonNote.txt
More file actions
1149 lines (599 loc) · 23.6 KB
/
Copy pathPythonNote.txt
File metadata and controls
1149 lines (599 loc) · 23.6 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
Python
Python is a general purpose language.It has been used in various feilds..
Fields:
1.Web Development.
2.Games
3.Data science
4.Machine learning.
5.Complex computing
6.App developoment
7.Analatycs
Installation
Install Python.exe from "python.org/downloads"
Install Pycharm IDE for python or Eclipse,NetBeans IDE.
Run Cmd..
>python
--"start programming"--
WORKING
Python is a Dynamically typed language,hence no need to Declare Data types for any Variables....
as like you assign a value to the variable it automatically senses that data type..However for getting inputs,
It always considers the input values as String..So, you may neeed to typecast everytime you getting the input
value from the user...
Typecasting:
In Python the typecasting is done by
int("input value")
float("input value")
str("input value")
Comments:
The python uses the "#" for comments,However it is single lines comments and not multi line comments..
#the variable gets the a value
Docstring:
Python has a special set of strings for the multiline comment interface..
"""
the variable gets the a value
"""
Variable Declaration:
In python we dont need to declare the data types..no need of semicolons, just a new line.....
x=15
y=10
z=x+y
print(z) //prints 25.
Variable Names:
A variable name must start with _ or alphabetic...it shouldn't start with number...
Numeric Types:
Python has three numeric types..
Int
Float
Complex..
String:
Python has variuos methods for string operation.Here the strings can be accesed by various methods..
"HELLO WORLD"
'HELLO WORLD'
both are same...
we can declare strings with either " " or ' ' ...both are same...
Example::
x="hello world"
print(x) // prints hello world
y='hello world'
print(y) // prints hello world
String functions::
Some of the string functions are....
strip()
//to remove the white spaces...
example:
x=" welcome "
print(x.strip()) //prints "welcome"
split()
//to split the string based on conditions..
//to split a string...
example:
x="welcome"
print(x.split("l")) //prints ["we","come"]
len()
//to find the length of the string...
example:
x="welcome"
print(len(x)) //prints 7
upper()
//converts to uppercase
exaple:
x="welcome"
print(x.upper()) //prints "WELCOME"
lower()
//converts to lowercase
example:
x="WELCOME"
print(x.lower()) //prints "welcome"
replace()
//replaces a character in the string with the given string
example:
x="welcome"
print(x.replace("w","b")) //prints "belcome"
to print a particular character at a particular position we use
x='welcome'
print(x[2]) //prints 'l'
to print certain characters from a point to another point we use
x='welcome'
print(x[1:3]) //prints 'elco'
Operators
python has several operators::
1.arithmetic operators
//python arithmetic operators are..
+ addition
- substraction
/ division
* multiplication
% modulas
//floor division
**exponential
2.assignment operators
= , += , -=, *= , /=, //=, **= , %=, &=, |=, <<=, >>=
3.comparision operators
== , !=, >, <, >=, <=
4.logical operators
and, or, not
5.membership operators
in, not in //returns true if some specialiased sequence of x in y
6.identity operators
is , is not //returns true if x is y, x is not y..
7.bitwise operators...
&, |, ~ , ^ , >> , <<
Python Collections
There are four collections are available in python..
1.list
List is a collection which is
1.ordered
2.changeable
3.duplicate members are allowed.
In Python Lists are written with square brackets...
example:
x=["apple","banana","orange"]
print(x) //prints ['apple','banana','orange']
The list() constructor:::
we can also use the list() to create and acccess a list...
example:
x=list(("banana","cherry","mango"))
append()::
to append or add or join a data..
example:
x=list(("apple","banana","orange"))
x.append("rose") //adds 'rose'
print(x) //prints ['apple','banana','orange','rose']
clear() -- x.clear() clears the list..
extend() -- y=list(("apple","orange"))--
-- x=list(("apple","mango"))--
-- x.extend(y) // joins the entire list with x..
-- print(x) //prints ['apple','orange','apple','mango']
copy() -- z=y.copy() //copy y's contents to z
reverse() //reverses a list
count() --print(x.count("apple")) // prints 1 //counts the specified element occurances..
index() -- prints the index of spcified element on its first occurance... // print(x.index("apple")) //prints 0
insert() -- inserts elements in a specified position..
example: x.insert(0,"mango") //inserts mango at position 0
remove()::
to remove a particular data from the list..
example:
x=list(("apple","banana","orange"))
x.remove("apple") //removes 'apple'
print(x) //prints ['banana','orange']
or
x.remove(x[0]) //removes 'apple'
print(x) //prints ['banana','orange']
pop() -- removes a position spcified element from list..
x.pop(5) // removes apple
sort() -- sorts a list Assending order by default...
arguments: reverse=True|False
key=function
example:
x.sort() //sorts the list assending order //by default reverse=False
x.sort(reverse=True) //sorts dessending order
x.sort(key=fun) //sorts based the function result
2.tuple
Tuple is a collection which is
1.ordered
2.non changeable
3.duplicate members are allowed
In python tuples are written with round brackets()
Tuple elements are unchangable..They are stable as you create them ..they cant be modified or changed in python like constant..
we cant perform remove,append,reverse,sort(),pop() anything....
Tuple() constructor::
x=tuple(("car","bike","van"))
print(x) //prints x elements
len() //prints the length of the tuple..
tuple elements are unchanged...
3.set
set is a collection which is
1.unordered
2.un indexed
3.No duplicate members are allowed
in python sets are written with curly brackets { }
x={"apple","orange","mango"}
print(x) // {'mango','apple','orange'} prints the elements randomly since it is unordered..
Unordered and Unindexed...No duplicate members re allowed..
set() :: constructor
the set() constructor is used with round brackets
x=set(("apple","banana","car"))
print(x) //prints the elements..
add()::
it is used to add any elements to the sets..
x.add("mango")
print(x) //prints {'apple','banana','car','mango'}
remove()::
removes any element..if the removing element is not in the list it throws an "KeyError"
x.remove("mango")
print(x) //prints {'apple','banana','car'}
len()::
to check the length
y=len(x)
print(y) //prints 3
copy()::
copies the elements to another variable
y=x.copy();
discard()::
used to remove any elements...if deleting element is not in the list it does nothing.
x.discard('mango') //deletes the element
clear()::
clears the entire set
4.dictionary
Dictionary is a collection which is
1.unordered
2.changeable and indexed
3.No duplicate members are allowed..
in python dictionaries are written with curley brackets { }
it has keys and values
example:
x={"car":"four_wheels","bike":"two_wheels":"flight":"three_wheels"}
print(x) //prints the elements
dict():: constructor
x=dict(car="four_wheel",bike="two_wheel",train="n_wheels")
print(x) //prints the elements
to an element---
x["auto"]="three_wheels"
del()::
to remove an item...
del(x["auto"]) //deletes the auto entry
len()::
to find the length
print(len(x)) //prints the length
Python Conditions
in all the python conditions we should use a colon (:) at the end to specify its a condition.
and we need to give indentation to the next line of code under all the consitional statements.
EX::
if a>b:
print(a)
if Statement:
in python we use thse statements to achieve if conditions..
i) if....ex-- if a>b :
ii) elif (else if)... in python elif is used instead of else if...
if a>b:
print(a)
elif b>a:
print(b)
iii) else.....
if a>b:
print(a)
elif b>a:
print(b)
else:
print("invalid")
Python Loops
python has two primitive loop commands
while lopp
for loop
while loop::
the key word is 'while'
example:
i=1
while i<6:
print(i)
i+=1
//prints 12345
break ::
the break statement in while loop used to break the function..
example:
i=1
while i<6:
print(i)
if i==3:
break
i+=1
//this stops the sequence when reaching 3...1 2 3 (break)
continue ::
the continue statement is used to skip the current iteration..
example:
i=0
while i<6:
i+=1
if i==3:
continue
print(i)
//this skips the number 3 when encountered..the continue statement is used to skip the current iteration..
for loop ::
like every other programming language for loop is used for looping certain statements
but it has different structure and syntax methods..
'for' is the keyword used...
using for loop we can iterate any python collections..
example::
machines=["car","bike","train","lorry"]
for x in machines:
print(x)
//prints car bike train lorry
break :: the break statement has the same functionality as in the while loop...as breaking the flow at a certain condition..
continue :: the continue statement has the same functionality as in the while loop as skip a specific iteration in flow..
range ::
range is used for specifing the condition or number of itereation of the for loop
example:
for x in range(6):
print(x)
//prints 0 1 2 3 4 5
the default starting of the range is 0
the default increment value is 1
we can change it by giving the range values....
example:
for x in range(1,5):
print(x) //prints 1 2 3 4 ..not 5
the default increment is 1..
We can sprcify the increment range by...
example:
for x in range(1,30,3): //the third element specifies the increment by 3
print(x)
recursion ::
recursive function method also supported by python..
the process of a function to call itself again and again to reach a result is called recursive function
Python Functions
A function is a block of code which is only executed on a function call...
we can pass data to a function called parameters...
we can get the output (return data) from the function called result...
in python a function is defined using the 'def' keyword...... indentation is must for everything in python
example:
def addition():
a=10
b=15
c=a+b
print(c)
addition() //function call //prints 25
Parameter Passing::
A python function can hold up multiple parameters
we should seperate each perameter by using a comma(,)
example:
def addition(x,y):
z=x+y
print(z)
addition(10,15) //function call //prints 25
return statement::
as like as other programming language python supports return statement...
'return'
example:
def addition(x,y):
return x+y
addition(10,15) //function call //prints 25
lambda functions::
an anonymous function is called as lambda function in python..
anonymous function is a function which has no names and used for a temporary cause..
it can hold multiple parameters but can execute only one expression..
in python the anonymous functins are defined using the keyword 'lambda'
example:
myfun=lambda i:i*2
myfun(2) //function call //prints 4
Python Array
Python dont have direct Array Support, instead we can use Lists as Arrays..All the list operations are considered as python Array
Operations....
Python Classes and Objects
Python is an object oriented programming language. It has class and object...A class is an blue print of the object.. Objects are created
for the classes and used to access the class members and methods..
Class Declaration::
class dog:
x=5
Object Creation::
d1=dog
print(d1.x) //prints 5
__init__::
the __init__ is used to initialize the class members or variables or states of an object
self ::
self is the referance for the class....
self means represants itself....
example:
class dog:
def __init__(self,name,age):
self.name=name
self.age=age
d1=dog("julie",2)
print(d1.name,d1.age) //prints julie 2
by using the __init__ method we can able to assign and modify and delete the class members or variables or instance...
delete Object Property ::
to delete an object property we need to use the "del" keyword
example:
del d1.age //delete the member age for the object d1
delete Object ::
to delete the object completely...
example:
del d1 //deletes the object from the entry
to modify ::
to modify the contents of the members...we use...
example:
d1.age=5 //updates the age as 5 for the object d1
Python Modules
A module in python is a library of codes..we can import the modules into our program whenever needed....
we need to store the codes as file and give filename extension as .py
Importing a module::
mymodule.py
import mymodule
a module can have multiple methods and classes and variables in it..we can use them according to our need
there are lot of predeveloped python libraries are available ...
to use a method of a module..we can use it like....
example:
import mymodule
x=mymodule.greetings("ramu")
print(x) //prints 'welcome ramu'
import specific method of a module::
we can import a specific method or codefile from a module..
keyword is "from"...
from mymodule import greetings
re-naming a module::
to rename a module,we use the keyword 'as'\
example::
import mymodule as my
dir()::
the dir() used to view the methods encapsulated by the module
example:
import mymodule
x=dir(mymodule)
print(x) //prints the methods in the modules
Date and Time in Python
for date and time operations there is a specific module is available in python
datetime::
this is module which consist of all the date and time operations
to view date and time::
example:
import datetime
x=datetime.datetime.now()
print(x) //prints 2018-07-09 10:43:29:45362
the datetime module has lots of methods prebuilded,we can use it by just calling them in our functions
PIP
PIP is the package manager for the python packages and modules
we can install and use variuos packages available from internet by using the pip
to install::
to install a new package we use ...
pip install camelcase //installs the camelcase package
the PIP allows us to consume various predeveloped packages available on the python index registry ...
the PIP can also be upgraded when needed from the cmd prompt
File Handling
the key method in file handling in python is open()
open()::
the open() method has two perameters 'filename' and 'mode'
there are four different modes for opening a file..
'r'=read mode..opens file for reading..throws error if file does not exist..
'a'=append mode..opens file for appending..creates new file if it does not exist..
'w'=write mode..opens file for writing..creates new file if it does not exist..
'x'=creates file..used to create a new file..throws error if file already exist
there is another two modes are available,,
't'=text mode/default mode
'b'=binary mode/images
read() ::
to read the contents of the file use "r"
example:
a=open("myfile.txt","r")
print(a.read()) //prints all the contents of the file
to read specific content of the file
example:
a=open("myfile.txt","r")
print(a.read(5)) //prints 5 letters from the file
to read a single line
example:
a=open("myfile.txt","r")
print(a.readline()) //prints single line of the file
we can read all the lines one by one by using the same command multiple times..
to read all the content using loop
example:
a=open("myfile.txt","r")
for i in a:
print(i) //prints all the content
write() ::
to write into a file use "w" or "a"
"a" adds new content with the existing content
"w" removes existing content and writes the new content (overrites)
using "w" (overrites if anything exists)
example:
a=open("myfile.txt","w")
a.write("hi i have deleted the content of this file") //removes existing content and writes new content
using "a" (adds the new content with the existing content)
example:
a=open("myfile.txt","a")
a.write("im adding this new line to the file") //adds the new content to the file
to create a new file
to create a new file we are using "x" "w" "a"
"x" to create a new file , returns error if file already exists
"w" to write into a file , creates new file if file does not exist
"a" to write into a file , creates new file if file does not exist
craete()::
example:
a=open("myfile.txt","x") //creates new file ,thorows error if already exist
example:
a=open("myfile.txt","w") //creates new file, if file does not exist
example:
a=open("myfile.txt","a") //creates new file if file does not exist
to Delete a file
to delete a file, we must import the "os"
delete()::
example:
import os
os.remove()::
example:
os.remove("myfile.txt") //removes the file
to check before deleting a files
example:
a=open("myfile.txt","w")
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("file does not exists")
to delete a folder
or.rmdir()::
example:
os.rmdir("myfolder") /deletes the entire folder
you can remove only empty folders
Memory Management in Python