-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython_Notes.py
More file actions
2890 lines (2195 loc) · 95.1 KB
/
Copy pathPython_Notes.py
File metadata and controls
2890 lines (2195 loc) · 95.1 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 Tutorials'''
'''1 Print Statement'''
# print("Hello World",7,"Shubh")
# print("2"*2)
# print(17-5)
# print(5)
# print("Shubh\nPathak")
# print("\"Shubh Pathak\"")
# print("Shubh", "Pathak", sep="~")
# print("Shubh", "Pathak", "Hello", sep="~", end="-\n")
'''2 Variables and Data Types'''
# a=1
# b="Shubh"
# c=True
# d=None
# e=1.0
# f=complex(1,2)
# print(a,b,c,d,e,f)
# print(type(a))
# print(type(b))
# print(type(c))
# print(type(d))
# print(type(e))
# print(type(f))
# Type Casting
# a=1
# b=2.5
# c=a+b
# d=complex(1,2)
# print() #throws error
# print(type(a+d))
# e=1.0
# print(int(a+b))
# print(type(c),c) #Implicit Type casting
# print(float(a)) #Explicit Type casting
# print(int(e))
'''3 Operators'''
# print(10+2)
# print(10-2)
# print(10*2)
# print(10/3)
# print(20//3) #Floor division
# print(10%3) #Modulo
# print(10**3) #Exponent
'''4 Type Casting'''
# a="2"
# b=int(a) #Explicit Type casting
# c="2"
# d=2.0
# e=2
# print(a)
# print(type(b))
# print(a+c)
# print(type(e+d)) #Implicit Type casting
'''5 User Input'''
# a=input("Enter Value")
# print(a)
# b=int(input("Enter Value"))
# print(b)
'''6 Strings (immutable)'''
# a='Shubh'
# print(a)
# a="Shubh"
# print(a)
# print(a[0],a[1],sep=".")
# a='"Shubh"'
# print(a)
# a="\"Shubh\""
# print(a)
# a='''Shubh
# Pathak''' #Multiline String
# print(a)
'''7 String Slicing'''
# name="Shubh,Pathak"
# print(len(name))
# print(name[0:5]) #0 included, 5 excluded
# print(name[:5])
# print(name[0:]) #same as name[0:len(name)]
# print(name[:]) #Same as name[0:len(name)]
# print(name[0:-3]) #this is same as print(name[0:len(name)-3])
# print(name[-3:-1])
# name="Shubh"
# print(len(name))
# print(name[-4:-2]) #this is same as print(name[1:3])
# print(type(name[-2:-4])) #this will give empty string
'''8 String Methods and Operations'''
''' Strings are immutable inplace'''
# a="Shubh"
# print(len(a)) #this is a function
# print(a.upper()) #this is a new string #Converts to uppercase #this is a method
# print(a.lower()) #Converts to lowercase
# a="!!!!!Shubh!!!!!$!!"
# print(a.rstrip("!")) #Returns new string after removing trailing characters (all occurence)
# print(a.strip("!")) #Returns new string after removing starting and trailing characters (all occurence)
# print(a.replace("Shubh","Pathak")) #replace one character with another
# print(a.replace("Pathak","Shubh"))
# a="Shubh Pathak"
# print(a.split(" ")) #Returns a list after splitting the string on the basis of entered parameter(Output:['Shubh', 'Pathak'])
# a=["shubh","pathak"]
# print(" ".join(a)) #this returns a list
# b="shubH"
# print(b.capitalize()) #Capitalize the 1st character and lower the other characters.
# c="Hello World in python"
# print(len(c))
# print(c.center(50,','))#aligns the string to center as per the parameter (Output:,,,,,,,,,,,,,,Hello World in python,,,,,,,,,,,,,,,)
# print(len(c.center(50)))
# d="Shubh Shubh Shubh 01"
# print(d.count("Shubh")) #Counts number of occurence of given character or string (Output:3)
# print(d.endswith("bh")) #Returns true if the string ends with the given parameter else false (Output:False)
# print(d.startswith("bh")) #Returns true if the string starts with the given parameter else false (Output:False)
# print(d.endswith("ub",1,4)) #Returns true if the string ends with the given parameter in the given range else false; 1 include, 4 excluded;
# print(d.find("ub")) #Gives index of first occurence of give value else -1 (Output:2)
# print(d.find("P")) #Gives index of first occurence of give value else -1 (Output:-1)
# print(d.index("ub")) #It is similar to find but it raises exception if value is not present in the string (Output:2)
# print(d.index("P")) #It is similar to find but it raises exception if value is not present in the string (Output:ValueError: substring not found)
# d="ShubhShubhShubh01"
# print(d.isalnum()) #returns true if string is alpha numeric ellse false it does not considers space as aplha or numeric(Output:True)
# print(d.isalpha()) #returns true if string is alphabet ellse false it does not considers space as aplha or numeric(Output:False)
# e="Shubh"
# print(e.isprintable()) #returns true if all characters of given string is printable else false(Output:True)
# e="Shubh\n"
# print(e.isprintable()) #returns true if all characters of given string is printable else false(Output:False since \n is not printable)
# e=" "#using space
# print(e.isspace()) #returns true if whitespace is present either using space bar or tab (Output: True)
# e=" "#using tab
# print(e.isspace()) #(Output: True)
# e="Shubh pathak is a boy"
# print(e.istitle()) #returns true is each first character of each word of the string is capital else false (Output:False)
# print(e.title()) #Converts given string into title case
# e="Shubh Pathak Is A Boy"
# print(e.istitle()) #returns true is each first character of each word of the string is capital else false (Output:True)
# e="shubh"
# print(e.isupper()) #returns true if all characters are in upper case (Output:False)
# print(e.islower()) #returns true if all characters are in lower case (Output:True)
# print(e.swapcase()) #Converts lower to upper and vice versa
'''9 If Else'''
#Conditional Operators: >,<,==,!=,>=,<=
# a=int(input("Enter your age: "))
# if(a>=18):
# print("You can drive")
# else:
# print("You cant drive")
'''10 Nested if else'''
# n=int(input("Enter a number: "))
# if(n>0):
# print("+ive")
# if (n%2==0):
# print("Even +ive")
# else:
# print("Odd +ive")
# elif(n==0):
# print("Zero")
# else:
# print("-ive")
# if (n%2==0):
# print("Even -ive")
# else:
# print("Odd -ive")
'''Exercise 1'''
'''Greeting Application'''
# import time
# t=time.strftime("%H:%M:%S")
# h=int(time.strftime("%H"))
# m=int(time.strftime("%M"))
# s=int(time.strftime("%S"))
# if(h>0 and h<12):
# print("Good Morning")
# elif(h>12 and h<16):
# print("Good Afternoon")
# elif(h>16 and h<20):
# print("Good Evening")
# else:
# print("Good Night")
# print(t)
'''11 MatchCase Statements'''
# Same as switch case of Java and C++
# a=int(input("Enter a number: "))
# if(a%2==0):
# f=1
# else:
# f=2
# match f:
# case 1:
# print("Even")
# case 2:
# print("Odd")
# case _: #Default case
# print("Invalid")
# break statement is not required in MatchCase
'''12 For Loop'''
# n="Shubh"
# for i in n:
# print(i)
# for i in range(1,11,2): #(start,end-1,step)
# if i%2==0:
# print(i, " Even")
# else:
# print(i," Odd")
# c=["Red","Green","Blue"]
# for i in c:
# print(i)
# for z in i:
# print(z)
# for i in range(-1,-20,-2): #works with neg index aswell
# print(i)
'''13 While Loop'''
# n=int(input("Enter a number: "))
# i=1
# while (i<=n):
# print(i)
# i=i+1
# i=5
# while(i>=0):
# print(i)
# i=i-1
# exit()
# else:
# print("Outside of while and inside else")
'''14 Break and Continue'''
# for i in range(1,12):
# if (i==11):
# break #Exit the loop
# print("5 x ",i ,"=", 5*i)
# for i in range(1,12):
# if (i==11):
# continue #Skip the iteration
# print("5 x ",i ,"=", 5*i)
'''15 Emulating Do While Loop'''
# n=int(input("Enter a Number: "))
# i=1
# while True:
# print(n,"x",i,"=",n*i)
# i=i+1
# if(i==11):
# continue #this iteration will be skipped
# if(i==15):
# break #loop will be exited
'''16 Functions'''
''' Function :can have many parameters ; exists on its own; called as: function() and #we create methods not functions in our program.
Eg: length(len) function to get the length
Method: the object is one of its parameters; belongs to a certain claass; called as: object.method().
Eg: append in a list is the usecase of method where object is passed a.append()'''
# def sum(l):
# c=0
# for i in l:
# c=c+i
# return c
# def average(l):
# c=sum(l)
# avg=c/len(l)
# return avg
# l={1,2,3,4,5,6}
# print(average(l))
# def multiply(a,b):
# pass #used to just define the function body
# a=10
# b=2
# def multiply(a,b):
# return a*b
# print(multiply(a,b))
'''17 Function Arguments and Return Statement'''
'''Types of Arguments:
1 Default Arguments; 2 Keyword Arguments; 3 Variable Length Arguments; 4 Required Arguments
'''
# # Required Arguments
# def average(a,b=1):
# c=a+b
# avg=c/2
# return avg
# print(average(1)) #value of a is required, b is user choice
# def average(a=1,b): #a default parameter can't follow a non default parameter
# c=a+b
# avg=c/2
# return avg
# print(average(1,2)) #throws SyntaxError: non-default argument follows default argument
# # Default Arguments
# def average(a=9,b=1):
# c=a+b
# avg=c/2
# return avg
# print(average(1)) #a will be assigned 1 and b will take the deafault argument 1
# # Keyword Arguments
# print(average(b=1,a=9)) #order of parameter is not necessary
# # Variable Length Arguments
# def average(*n): # *n is taken as tuple and **n is taken as dictionary
# print(type(n)) #Output: <class 'tuple'>
# c=0
# for i in n:
# c=c+i
# avg=c/len(n)
# return avg
# print(average(1,2,3,4)) #we can pass any number of arguments
# def name(**l): #**l is taken as dictionary
# print(type(l))
# name(n1="Shubh",n2="Ananya")
# def s(a,b):
# print(a)
# l=[1,2,3,4]
# s(l,2)
# *args and **kwargs
'''18 List: Ordered Collection of Homogeneous Data Items stored in [] and are mutable
alphabets =["a", "b", "c", "d", "e"]
[0] [1] [2] [3] [4]
alphabets =["a", "b", "c", "d", "e"]
[-5] [-4] [-3] [-2] [-1] '''
# l=[1,2,3]
# print(type(l)) #Output:<class 'list'>
# print(l[0],l[1],l[2],sep="-") #Indexing starts from 0
# l=[1,"2",True,4.0,None] #Can store different data types
# print(l[0],l[1],l[2],l[3],sep="-")
# print(len(l))
# print(l[-2]) #Same as l[len(l)-2]
# print(l[len(l)-2])
# print(l[3])
# print(1 in l) #Used to find an element in list returns true or false same thing applies for Strings
# #List Slicing listName[start : end : jumpIndex]
# l=[1,2,3]
# print(l[0:3]) #Start from 0 and 3 is excluded same as string
# print(l[0:-2]) #Same as l[0:len(l)-2]
# print(l[0:len(l):2]) #Jump 2
# print(l[0:]) #Same as l[0:len(l)]
# print(l[:2]) #Same as l[0:2]
# print(l[:]) #Same as l[0:len(l)]
# #List Comprehension : List = [Expression(item) for item in iterable if Condition]
# l=[i for i in range(10)]
# print(l)
# l=[i*i for i in range(10)]
# print(l)
# l=[i for i in range(10) if i%2==0]
# print(l)
# l=[1,2,3,4,5,6,7,8,9,10]
# l1=[i**2 for i in l if i%2==0]
# print(l1)
# l=['1','2','3','4']
# s="".join(l) #used to convert list to string
# print(s)
# print(list(s)) #used to convert string to list
'''19 List Methods'''
# l=[1,2,3,4,5,6,7,8,9,10]
# print(l)
# l.append(11) #used to add elements
# print(l)
# l.sort() #used to sort list in ascending order; original list is updated
# print(l)
# l.reverse() #reverse list; original list is updated
# print(l)
# l.sort(reverse=True) #used to sort list in descending order; original list is updated
# print(l)
# print(l.index(7)) #returns index of first occurence of given element
# print(l.index(7,2,7)) #This will give index 6 since python will search 7 in between index 2(included) and 7(excluded)
# print(l.index(7,2,5)) #This will give error since python will search 7 in between index 2(included) and 5(excluded)
# print(l.count(1)) #returns num of times an element is present in the list
# l=[1,2,3,4,5,6,7,8,9,10]
# m=l #m is a reference of l any change in m will change l #shallow copy
# m[0]=0 #0th index of l will be changed
# print(l)
# l=[1,2,3,4,5,6,7,8,9,10]
# m=l.copy() #used to create copy of list #deep copy
# m[0]=0 #0th index of l will be changed
# print(m)
# print(l)
# l.insert(2,100) #insert an element at specified index .insert(index,element)
# print(l)
# m=[100,200,300]
# l.extend(m) # join second list to first list i.e l is changed
# print(l)
# print(m)
# k=l+m #this will not edit l but create a new list k
# print(l)
# print(m)
# print(k)
'''20 Tuples: Ordered Collection of Heterogeneous Data Items stored in () and are immutable'''
# t=(1,2,3,4,5)
# print(type(t), t)
# t=(1)
# print(type(t), t) #this will return type as int so we need to add , after 1 element to make sure its tuple
# t=(1,)
# print(type(t), t) #this will return type as tup so we need to add , after 1 element to make sure its tuple
# t[0]=11
# print(t) #This will give error as tuple is immutable
# print(t[0:len(t)])
# print(t[0:-2]) #Same as t[0:len(t)-2]
# print(t[0:len(t)-2])
# print(t[0:len(t):2]) #Jump 1 elements
#Tuple unpacking
# t=(1,2,3,4,5)
# (a,b,c,d,e)=t #tuple unpacking
# print(a)
# print(b)
# print(c)
# print(d)
# print(e)
# def add(*args):
# a=args[0]
# print(a)
# (a,b,c)=args #tuple unpacking
# print(a)
# print(b)
# print(c)
# add(1,2,3)
# fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
# (green, yellow, *red) = fruits #last three will be added in red as list
# print(green)
# print(yellow)
# print(red)
#Tupple Zipping
# t1=(1,2,3)
# t2=(4,5,6)
# t3=zip(t1,t2)
# print(type(zip(t1,t2)),zip(t1,t2))
# l=set(t3)
# print(l)
# for i in l:
# print(i)
#Tupple Unzipping
# t1=(1,2,3)
# t2=(4,5,6)
# t3=zip(t1,t2)
# c1,c2=zip(*t3)
# print(c1)
# print(c2)
'''21 Tuple Methods'''
# t=(1,2,3,4,5,6,7,8)
# print(t)
# l=list(t) #To edit a tuple convert it to list and then performs functions on it and then convert it back to tuple
# l.append(9)
# l.pop(2) #this will remove element at inex 2
# t=tuple(l)
# print(t)
# t2=(9,10,11)
# t3=t+t2 #Creating a new tuple
# print(t3)
# print(t.count(7)) #Count number of occurence of given element in tuple
# print(t.index(7)) #returns index of first occurence of given element
# print(t.index(7,2,7)) #This will give index 6 since python will search 7 in between index 2(included) and 7(excluded)
# print(t.index(7,2,5)) #This will give error since python will search 7 in between index 2(included) and 5(excluded)
'''Exercise 2'''
'''Create a Quiz'''
# import random
# Ques=["What country has the highest life expectancy?","Where would you be if you were standing on the Spanish Steps?","Which language has the more native speakers: English or Spanish?","What is the most common surname in the United States?","What disease commonly spread on pirate ships? ","Who was the Ancient Greek God of the Sun? ","What was the name of the crime boss who was head of the feared Chicago Outfit?","What year was the United Nations established? ","Who has won the most total Academy Awards?","What artist has the most streams on Spotify?"]
# Ans=["Hong Kong","Rome","Spanish","Smith","Scurvy","Apollo","Al Capone","1945","Walt Disney","Drake",]
# l=[] #List to store ques numbers
# p=0
# while(True):
# n=input("Enter y to play game else enter n: ")
# if n=='n':
# break
# else:
# q=random.randint(0,len(Ques)-1) #generates random number between the given range both included
# l.append(q)
# print(Ques[q])
# a=input("Enter Answer: ")
# if a==Ans[q]:
# print("Correct answer.Bravo!")
# p=p+100
# print("Current Points: ",p)
# if a!=Ans[q]:
# print("Wrong answer.Try again!")
# p=p-100
# print("Current Points: ",p)
# if p<0:
# p=0
# print("Final Points: ",p)
'''22 f Strings'''
# s="My name is {} and I am {} years old."
# n="Shubh"
# a="22"
# print(s.format(n,a)) #String formatting old way
# print(f'My name is {n} and I am {a} years old..') #f strings new way
# print(f'My name is {{n}} and I am {{a}} years old..') #f strings new way
# a=2.333333
# print(a)
# print("{:.2f}".format(a))
# print(f"{a:.2f}")
'''23 DocStrings and Pep-8'''
# def sum(l):
# '''Returns sum of all elements of list''' #written right below function name and right above function body
# c=0
# for i in l:
# c=c+i
# return c
# def average(l):
# '''Returns average of the list passed'''
# c=sum(l)
# a=c/len(l)
# return a
# l=[1,2]
# average(l)
# print(average.__doc__)
# print(sum.__doc__)
#PEP- 8: Python Enhancement Proposals
# import this
# The Zen of Python, by Tim Peters
# Beautiful is better than ugly.
# Explicit is better than implicit.
# Simple is better than complex.
# Complex is better than complicated.
# Flat is better than nested.
# Sparse is better than dense.
# Readability counts.
# Special cases aren't special enough to break the rules.
# Although practicality beats purity.
# Errors should never pass silently.
# Unless explicitly silenced.
# In the face of ambiguity, refuse the temptation to guess.
# There should be one-- and preferably only one --obvious way to do it.
# Although that way may not be obvious at first unless you're Dutch.
# Now is better than never.
# Although never is often better than *right* now.
# If the implementation is hard to explain, it's a bad idea.
# If the implementation is easy to explain, it may be a good idea.
# Namespaces are one honking great idea -- let's do more of those!
'''24 Recursions'''
# def factorial(n):
# if n==0 or n==1:
# return 1
# else:
# return n*factorial(n-1)
# a=int(input("Enter number: "))
# print(factorial(a))
# def fibonacci(n):
# if n==0:
# return 0
# if n==1 or n==2:
# return 1
# else:
# return fibonacci(n-1)+fibonacci(n-2)
# a=int(input("Enter number: "))
# print(fibonacci(a))
'''25 Sets are unordered collection of data items, enclosed within curly brackets {}.
Sets are unchangeable, and do not contain duplicate items.'''
# s={2,4,5,3,1}
# print(s)
# i={1,"2",False,3.9,3.9}
# print(i) #only single 3.9 will be printed
# a={} #this is dictionary not an empty set
# print(type(a)) #this will give <class 'dict'>
# a=set() #this is how we create empty set
# print(type(a)) #this will give <class 'set'>
'''26 Set Methods'''
# s1={10,17,22,34}
# s2={5,13,34,49}
# print(s1.union(s2)) #this will give union of both the set , this will create new set
# print(s1.intersection(s2)) #this will give intersection of both the set, this will create new set
# s1.update(s2) #this will add elements of s2 in s1 same as list extend method
# print(s1)
# # print(s2)
# s1.intersection_update(s2) #this will update s1 with elements that are common in both sets
# print(s1)
# print(s2)
# print(s1.symmetric_difference(s2)) #this will return (s1 union s2)-(s1 intersection s2)
# s1.symmetric_difference_update(s2) #this will update s1 with (s1 union s2)-(s1 intersection s2)
# print(s1)
# print(s1.difference(s2)) #this will return s1-s2
# s1.difference_update(s2) #this will update s1 with s1-s2
# print(s1)
# s1={1,2,3,4}
# s2={2,3}
# s3={5}
# print(s1.isdisjoint(s3)) #checks if items of given set are present in another set
# print(s1.issuperset(s2)) #checks if all the items of a particular set are present in the original set
# print(s2.issubset(s1)) #checks if all the items of the original set are present in the particular set
# s1={1,2,3,4}
# s2={6}
# s1.add(5) #this will add only single element in set
# print(s1)
# s1.update(s2) #this will add s2 to s1
# print(s1)
# s1.remove(6) #this will remove an element from set. If element is not present in set and error will be thrown.
# print(s1)
# print(s1)
# s1.discard(5) #this will also remove an element from set. If element is not present in set and no error will be thrown.
# print(s1)
# p=s1.pop() #this removes the last item of the set but we don’t know which item gets popped as sets are unordered.
# print(s1)
# print(p)
# # del s2 #del keyword deletes the set entirely.
# # print(s2)
# # s2.clear() #this clears all items in the set and prints an empty set.
# # print(s2)
# print(6 in s2) #this check if an item exists in the set or not
'''27 Dictionary '''
''' They are ordered collection of data items.
They store multiple items in a single variable.
Dictionary items are key-value pairs that are separated by commas and enclosed within curly brackets {}'''
# d={
# 1:"Matt",
# 2:"Rob",
# 3:"Jack",
# 4:"Dolph"
# }
# print(d)
# print(d[1])
# print(d.get(1))
# print(d[5]) #if key does not exist it will give error (Output: KeyError: 5)
# print(d.get(5)) #if key does not exist it will give none (Output: None)
# print(d.keys()) #print all the keys in the dictionary
# print(d.values()) #print all the values in the dictionary
# for k in d.keys():
# print(f"For Key {k} value is {d[k]}")
# print(d.items()) #print all the key-value pairs in the dictionary
# for k,v in d.items():
# print(f"For Key {k} value is {v}")
'''28 Dictionary Methods'''
# d1={
# 1:"Matt",
# 2:"Rob",
# 3:"Jack",
# 4:"Dolph"
# }
# d2={
# 5:"Mark",
# 6:"Jey",
# 7:"Jimmy"
# }
# d3={} #empty dict
# d1.update(d2) #this will add d2 to d1
# print(d1)
# print(d2)
# d2.clear() #this removes all items from the dict d2
# print(d2)
# d2.pop(6) #this removes the item with corresponding key passed
# print(d2)
# d2.popitem() #this removes the last item from dict
# print(d2)
# del d3 #del keyword deletes the dict entirely.
# print(d3)
# del d1[1] #this deletes the item with corresponding key passed
# print(d1)
'''29 for and while Loop with else'''
# for i in range(0,4):
# print(i)
# else: #this else will only be executed when the all all the iterations are completed
# print("Out of loop")
# for i in range(0,4):
# print(i)
# if (i==2):
# break
# else: #this time else will not be executed since the loop is terminated in between and all iterations are not completed
# print("Out of loop")
#Similarly for while loop else will only execute if all iterations are done completely
# i=0
# while(i<5):
# print(i)
# i=i+1
# else: #this else will only be executed when the all all the iterations are completed
# print("Out of loop")
# i=0
# while(i<5):
# print(i)
# i=i+1
# if i==2:
# break
# else: #this time else will not be executed since the loop is terminated in between and all iterations are not completed
# print("Out of loop")
'''30 Exception Handling'''
# n=input("Enter a number: ")
# print(f"Multiplication table of {n}:")
# try:
# for i in range(1,11):
# print(f"{int(n)} x {i} = {int(n)*i}")
# # except Exception as e:
# # print(e)
# except :
# print("Invalid input!") #we can also give custon error msg
# print("Some other piece of code!!")
# print("Some other piece of code!!")
#Handling multiple exceptions
# try:
# n=int(input("Enter a number: ")) #if error occurs here ValueError will be triggered
# a=(1,2)
# print(a[n]) #if error occurs here IndexError will be triggered
# except ValueError:
# print("Invalid value entered!")
# except IndexError as i:
# print("Index out of bound!!")
# print(i)
'''31 Finally Clause'''
# def func(n):
# try:
# a=[1,2,3,4]
# return(a[int(n)])
# except ValueError as v:
# return v
# except IndexError as i:
# return i
# finally:
# print("Finally is always be executed!!") #this will always be executed in any situation
# # print("Finally is always be executed!!") #but this will not be excuted since it comes after return statetment this is the diff between code written in finally block and code written normally
# n=input("Enter index: ")
# print(func(n))
'''32 Raising custom errors'''
# a=int(input("Enter number between 4 and 6 : "))
# if (a<4 or a>6):
# raise ValueError("Value should be between 4 and 6") #raise keyword help us to raise custom errors
# define Python user-defined exceptions
# class InvalidAgeException(Exception):
# "Raised when the input value is less than 18"
# pass
# # you need to guess this number
# number = 18
# try:
# input_num = int(input("Enter a number: "))
# if input_num < number:
# raise InvalidAgeException
# else:
# print("Eligible to Vote")
# except InvalidAgeException:
# print("Exception occurred: Invalid Age")
'''Exercise 3'''
'''Coding:
# if the word contains atleast 3 characters, remove the first letter and append it at the end
# now append three random characters at the starting and the end
# else:
# simply reverse the string
# Decoding:
# if the word contains less than 3 characters, reverse it
# else:
# remove 3 random characters from start and end. Now remove the last letter and append it to the beginning
# Your program should ask whether you want to code or decode'''
# import random
# import string
# def encode(s):
# e=""
# l=[]
# if len(s)<=3:
# e=s[::-1]
# return e
# else:
# s=s[1:]+s[0]
# z=""
# for i in range(0,3):
# n=random.choice(string.ascii_letters) #gives random letters
# z=z+n.lower()
# s=z+s+z
# return s
# def decode(s):
# d=""
# l=[]
# if len(s)<=3:
# e=s[::-1]
# return e
# else:
# s=s[-4]+s[3:-4]
# return s
# s=input("Enter a string: ")
# print("Encoded Text: ",encode(s))
# print("Decoded Text: ",decode(encode(s)))
'''33 Short Hand if else'''
# a=3
# b=3
# print("B is greater") if b>a else print("A is greater") if a>b else print("A is equal to B")
# c=1 if b>a else -1 if a>b else 0
# print(c)
# above code is similar to below code
# if b>a:
# c=1
# elif a>b:
# c=-1
# else:
# c=0
# print(c)
'''34 Enumerate Function'''
# a=[1,2,3,4,5,6]
# for index,m in enumerate(a): #this get the index and value of each element in the sequence
# print(index,m)
# if(index==3):
# print("Index 3")
# for index,m in enumerate(a,start=1): #By default, the enumerate function starts the index at 0 but we can change this using start parameter
# print(index,m)
# if(index==3):
# print("Index 3")
'''35 Virtual Environment'''
'''A virtual environment is a tool used to isolate specific Python environments on a single machine,
allowing you to work on multiple projects with different dependencies and packages without conflicts.'''
#For Windows
# for making a new environment (same)-> python -m venv dir_name
# for activation of that environment-> dir_name\Scripts\activate.bat(for shell)
# for activation of that environment-> dir_name\Scripts\activate.ps1(for powershell)
# for deactivation of that environment-> deactivate
# for checking version in windows-> python --version