-
Notifications
You must be signed in to change notification settings - Fork 0
/
Learn_Python_SM.py
1375 lines (1077 loc) · 33 KB
/
Learn_Python_SM.py
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
print("Hello World")
print('\n\n')
#Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
#Python is used for: 1.web development (server-side), 2.software development, 3.mathematics, 4.system scripting.
#1
'''
#1-Python Identation
if 5 > 2:
print("Five is greater than two!")
#print("Five is greater than two!")
'''
"""
#2-Comment
This is a comment
written in
more than just one line
"""
'''
#3-Variable
x = "Python is "
y = "awesome"
z = x + y
print("The " + z)
x = 'Md'
y = 'SuMon'
print('My name is ' + x + ' ' + y)
'''
'''
#4-Global_Varial
x = "awesome" #it's a global variable
def myfunc():
x = "fantastic" #It's a variable as the same name as global variable but it's not a global variable.
print("Python is " + x)
myfunc()
print("Python is " + x)
'''
'''
#5-Global_Keyword
def myfunc():
global x
x = "fantastic" #It's became global variable by using global keyword.
myfunc()
print("Python is " + x)
'''
'''
#6-Python Data Type
"""
Data Type in python.
1.Text Type: str
2.Numeric Types: int, float, complex
3.Sequence Types: list, tuple, range
4.Mapping Type: dict
5.Set Types: set, frozenset
6.Boolean Type: bool
7.Binary Types: bytes, bytearray, memoryview
"""
#To get data type.
x = 5.3j
print(type(x))
'''
'''
#7-Python Number
x = 1 # int
y = 2.8 # float
y2= 35e3 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(y2))
print(type(z))
'''
'''
#8-Type conversion
x = 1 # int
y = 2.8 # float
z = 1j # complex
print("Before Converting")
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print("\n\nAfter Converting")
print(a)
print(b)
print(c)
print
print(type(a))
print(type(b))
print(type(c))
'''
'''
#9-Random Number
import random
print(random.randrange(1, 10))
'''
'''
#10-Python Casting
#int()
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
#float()
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
#str()
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
'''
"""
#11-Python String
#Value_assign
a = "Hello"
print(a)
print(a[1]) #String are arrays
#Multiple_String
b = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print("\n\n" + b)
#Slicing
c = "Hello, World!"
print("\n\n" + c[2:5])#(Starting from index (2) to before (5))
print("\n" + c[-5:-2])#Negative Indexing(Starting from index (-5) to before (-2))
#String Length
print("\n\n")
print(len(c))
#String Methods_The strip() method removes any whitespace from the beginning or the end:
d = " Hello, World! "
print(d.strip()) # returns "Hello, World!" and remove whitespace from Begining & Ending.
print(d.lower())
print(d.upper())
print(d.replace("H", "J"))
print(d.split(",")) # returns ['Hello', ' World!'] #The split() method splits the string into substrings if it finds instances of the separator:
#Check String
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print("\n\n")
print(x) #True
y = "ain" not in txt
print(y) #False
#String Concatenation
a = "Hello"
b = "World"
print(a + " " + b + "!")
c = a + " " + b
print(c)
print("\n\n")
#String Format_As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
print("\n\n")
age = 23
name = "SuMon"
txt = "My name is {}, I am {}"
print(txt.format(name, age))
txt2 = "My name is {1}, I am {0}"
print(txt2.format(age, name))
print('\n\n')
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
print("\n\n")
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
print("\n\n")
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
print("\n")
txt1 = 'We are the so-called "Vikings" from the north.'
print(txt1)
print("\n\n")
"""
'''
#12-Python Booleans_Booleans represent one of two values: True or False.
print("Booleans represent one of two values: True or False.")
print(10 > 9)
print(10 == 9)
print(10 < 9)
print("----------------1\n\n")
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
print("----------------2\n\n")
#Evaluate Values_The bool() function allows you to evaluate any value, and give you True or False in return,
print(bool("Hello"))
print(bool(15))
print("----------------3")
#Evaluate Variables
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
print("----------------4")
#Which value is true or false
m = """Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones."""
print(m)
print("\n\n")
n = """In fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False."""
print(n)
print("\n\n")
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
print("\n\n")
print("The following will return False:")
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
print("\n\n")
print("----------------5\n\n")
o = """One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False:"""
print(o)
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
print("----------------6")
print("\n\n")
#Functions can Return a Boolean
def myFunction() :
return True
print(myFunction())
print("_________7\n\n")
#Question: Print "YES!" if the function returns True, otherwise print "NO!":
def myFunction() :
return False
if myFunction():
print("YES!")
else:
print("NO!")
#Python also has many built-in functions that returns a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
p = 200
print(isinstance(p, int))
print(isinstance(p, float))
'''
'''
#13-Python Operator
x = 5
y = 2
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y) #1_____Residue Part
print(x ** y) #25____x to the power y
print(x // y) #2_____How many time it can be devided.
#For more details: https://www.w3schools.com/python/python_operators.asp
'''
'''
#14-Python List
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist)
print("\n\nAccess Items:")
print(thislist[1])
print("\n\nNegative Indexing:")
print(thislist[-1])
print("\n\nRange of Indexes:")
print(thislist[2:5])
print(thislist[:4]) #index 0 to before 4
print(thislist[2:]) #index 2 to last
print("\n\nRange of Negative Indexes:")
print(thislist[-4:-1])
print("\n\nChange Item Value:")
thislist[1] = "blackcurrant"
print(thislist)
print("\n\nLoop through a list:")
for x in thislist:
print(x)
print("\n\nCheck if Item Exists:")
if "appl" in thislist:
print("Yes, 'apple' is in the fruits list")
else:
print("No, It is not in this list")
"""
a = input("Enter your Item : ")
if a in thislist:
print("Yes " + a + " is in thislist")
else:
print("No " + a + " is not in thislist")
"""
print("\n\nList Length:")
print(len(thislist))
print("\n\nAdd Items:")
thislist.append("strawberry")
print(thislist)
print("\n\nAdd Items in Specific Index:")
thislist.insert(1, "strawberry")
print(thislist)
print("\n\nRemove Items:")
thislist.remove("kiwi")
print(thislist)
print("\n\npop Method:")
#The pop() method removes the specified index, (or the last item if index is not specified):
thislist.pop()
print(thislist)
print("\n\ndel keyword remove a specific index:")
del thislist[0]
print(thislist)
print("\n\nMethod of Copy a List:")
mylist = thislist.copy()
print(mylist)
mylist1 = list(thislist)
print(mylist1)
print("\n\nclear method empty the list")
thislist.clear()
print(thislist)
print("\n\nJoin Two Lists:")
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
print("\n\nAppend list2 into list1:")
for x in list2:
list1.append(x)
print(list1)
print("\n\nUse the extend() method to add list2 at the end of list1:")
list1.extend(list2)
print(list1)
print("\n\nThe list() Constructor:")
thislist1 = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist1)
'''
'''
#15-Python Tuples
#Same as list, But tuples are written with round brackets.
print("Method of Indexes: ")
thistuple = ("apple", "banana", "cherry")
print(thistuple)
print(thistuple[1])
print(thistuple[-1])
print(thistuple[2:5])
print(thistuple[-4:-1])
print("\n\nChange Tuple Values: ")
x = ("apple", "banana", "cherry")
print(x)
y = list(x)
print(y)
y[1] = "kiwi"
x = tuple(y)
print(x)
print("\n\nLoop Through a Tuple: ")
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
print("\n\nCheck if Item Exists: ")
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
print("\n\nTuple Length: ")
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
"""
print("Add Item is not support in tuple: ")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
"""
print("\n\nCreate Tuple With One Item: ")
thistuple1 = ("apple",) #use comma after value is necessary.
print(type(thistuple1))
tl1 = list(thistuple1)
print(tl1)
#NOT a tuple
thistuple2 = ("apple")
print(type(thistuple2))
tl2 = list(thistuple2)
print(tl2)
print("Because it was a string")
"""
print("\n\nRemove Items: ")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
"""
print("\n\nJoin Two Tuples: ")
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
print("\n\nThe tuple() Constructor: ")
#It is also possible to use the tuple() constructor to make a tuple.
# Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
'''
#16-Python Sets
#Sets are unordered.
#A set is a collection which is unordered and unindexed.
#In Python sets are written with curly brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
print("\n\nAccess Item: ")
for x in thisset:
print(x)
print('\n\nCheck if "banana" is present in the set:')
print("banana" in thisset)
print("\n\nChange Items: ")
print("Once a set is created, you cannot change its items, but you can add new items.")
print("\n\nAdd Items: ")
print("Add an item to a set, using the add() method:")
thisset.add("orange") #It will be assign in any index of the set. Index will change again and again when we print.
print(thisset)
print("\nAdd multiple items to a set, using the update() method: ")
thisset.update(["pineapple", "mango", "grapes"]) #It will be assign in any index of the set. Index will change again and again when we print.
print(thisset)
print("\n\nGet the Length of a Set: ")
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
print("\n\nRemove Item: ")
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
print("If the item to remove does not exist, remove() will raise an error.")
print("\nRemove Item by using discard: ")
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
print("If the item to remove does not exist, discard() will NOT raise an error.")
print("\nRemove the last item by using the pop() method: ")
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
#Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
print("\nThe clear() method empties the set: ")
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
"""
print("\nThe del keyword will delete the set completely: ")
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
"""
print("\n\nJoin Two Sets: ")
print("You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:" )
print("\nThe union() method returns a new set with all items from both sets: ")
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
print("\nThe update() method inserts the items in set2 into set1: ")
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
print("Both union() and update() will exclude any duplicate items.")
print("\n\nThe set() Constructor: ")
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
'''
#17-Python Dictionaries
print("A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print("\n\nAccessing Items: ")
x = thisdict["model"]
x = thisdict.get("model")
print("\n\nChange Values: ")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2020
print(thisdict)
print("\n\nLoop Through a Dictionary: ")
for x in thisdict:
print(x)
print(thisdict[x])
print("\n\nAnother format: ")
for x in thisdict:
print(x + " " + str(thisdict[(x)]))
print("\n\nYou can also use the values() method to return values of a dictionary:")
for x in thisdict.values():
print(x)
print("\n\nLoop through both keys and values, by using the items() method:")
for x, y in thisdict.items():
print(x, y)
print("\n\nCheck if Key Exists: ")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
print("\n\nDictionary Length: ")
print(len(thisdict))
print("\n\nAdding Items: ")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
print("\n\nRemoving Items: ")
#The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
#The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
#The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
#The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
#print(thisdict) #this will cause an error because "thisdict" no longer exists.
#The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
print("\n\nCopy a Dictionary: ")
#Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
#Another way to make a copy is to use the built-in function dict().
#Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
print("\n\nNested Dictionaries: ")
print("A dictionary can also contain many dictionaries, this is called nested dictionaries.")
print("Create a dictionary that contain three dictionaries:")
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print("\nAnother Way: ")
print("Create three dictionaries, then create one dictionary that will contain the other three dictionaries:")
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print("\n\nThe dict() Constructor: ")
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
'''
'''
#18-Python If ... Else
print("Python supports the usual logical conditions from mathematics: ")
print("Equals: a == b\nNot Equals: a != b\nLess than: a < b\nLess than or equal to: a <= b\nGreater than: a > b\nGreater than or equal to: a >= b")
print("\n\nIf_elif statement: ")
a = 33
b = 200
if b > a:
print("b is greater than a")
elif a == b: #The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
print("a and b are equal")
print("\n\nElse Statement: ")
print("The else keyword catches anything which isn't caught by the preceding conditions.")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
print("\n\nShort Hand If: ")
print("If you have only one statement to execute, you can put it on the same line as the if statement.")
print("\nOne line if statement:")
if a > b: print("a is greater than b")
print("\n\nShort Hand If ... Else: ")
print("If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:")
print("\nOne line if else statement: ")
a = 2
b = 330
print("A") if a > b else print("B")
print("\nOne line if else statement, with 3 conditions: ")
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
print("\n\nAnd: ")
print("Test if a is greater than b, AND if c is greater than a:")
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
print("\n\nOr: ")
print("Test if a is greater than b, OR if a is greater than c:")
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
print("\n\nNested If: ")
print("You can have if statements inside if statements, this is called nested if statements.")
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
print("\n\nThe pass Statement: ")
a = 33
b = 200
if b > a:
pass
#pass statement to avoid getting an error.
'''
'''
#19-Python While Loops
"""Python Loops
Python has two primitive loop commands:
while loops
for loops"""
print("The while Loop: ")
print("With the while loop we can execute a set of statements as long as a condition is true.")
i = 1
while i < 6:
print(i)
i += 1
print("\n\nThe break Statement: ")
print("With the break statement we can stop the loop even if the while condition is true: ")
print("Exit the loop when i is 3: ")
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
print("\n\nThe continue Statement: ")
print("With the continue statement we can stop the current iteration, and continue with the next: ")
print("Continue to the next iteration if i is 3: ")
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
print("\n\nThe else Statement: ")
print("With the else statement we can run a block of code once when the condition no longer is true: ")
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
'''
'''
#20-Python For Loops
print("Print each fruit in a fruit list: ")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
print("\nLooping Through a String: ")
for x in "banana":
print(x)
print("\nThe break Statement: ")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
print("Another way: ")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
print("\nThe continue Statement: ")
print("Do not print banana: ")
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
print("\nThe range() Function")
for x in range(6):
print(x)
print("Using the start parameter: ")
for x in range(2, 6):
print(x)
print("Increment the sequence with 3 (default is 1): ")
for x in range(2, 30, 3):
print(x)
print("\nElse in For Loop: ")
print("Print all numbers from 0 to 5, and print a message when the loop has ended: ")
for x in range(6):
print(x)
else:
print("Finally finished!")
print("\nNested Loops: ")
print("A nested loop is a loop inside a loop.")
print("Print each adjective for every fruit: ")
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
print("\nThe pass Statement: ")
for x in [0, 1, 2]:
pass
'''
'''
#21-Python Functions
"""A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result."""
print("Creating a Function: ")
print("In Python a function is defined using the def keyword: ")
def my_function():
print("Hello from a function")
print("\nCalling a Function: ")
print("To call a function, use the function name followed by parenthesis: ")
def my_function1():
print("Hello from a function")
my_function1()