-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
3037 lines (2820 loc) · 131 KB
/
main.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
# Python - About
"""
- Python is a server-side programming language.
- Python can be used for many things: {
* Web Development (server-side)
* Software Development
* Machine Learning
* AI
* Mathematics
* System Scripting
}
- This documentation uses Python 3
- Python files have the file extension .py (filename.py)
"""
# Documentation - About
"""
- This python documentation file is written by Swordax
- Find me on github: https://github.com/SwordaxSy/
- Find me on discord (Swordax#5756): https://discord.com/users/465453058667839499/
- My website: https://swordax.netlify.app
- Documentation Repo: https://github.com/SwordaxSy/Python/
- Documentation Source: https://w3schools.com/python/
- Documentation Info: {
1- created on: 5th of Jan, 2022
2- completed on: 9th of Jan, 2022
3- total lines: 3037
4- total chapters: 25
}
"""
# Documentation - Bibliography
"""
{
"[1] Intro": [
"[1.1] getting started",
"[1.2] syntax",
"[1.3] comments",
"[1.4] print statement",
"[1.5] input"
],
"[2] Variables": [
"[2.1] intro to variables",
"[2.2] casting",
"[2.3] overwriting variables",
"[2.4] get variable value data type",
"[2.5] string variable declaration",
"[2.6] variable naming rules",
"[2.7] multi-name variable naming style",
"[2.8] assigning multiple values to variables",
"[2.9] outputting variables",
"[2.10] variable scope"
],
"[3] Data Types": [
"[3.1] intro to data types",
"[3.2] data types in real code",
"[3.3] setting specific data type (casting)"
],
"[4] Numbers": [
"[4.1] numeric data types",
"[4.2] numeric type conversion",
"[4.3] random numbers"
],
"[5] Strings": [
"[5.1] basic strings",
"[5.2] get a specific character in a string",
"[5.3] the len() method",
"[5.4] the in keyword",
"[5.5] slicing strings",
"[5.6] string modification",
"[5.7] string format() method",
"[5.8] escape characters",
"[5.9] string methods"
],
"[6] Booleans": [
"[6.1] intro to booleans",
"[6.2] evaluating expressions",
"[6.3] booleans in conditional statements",
"[6.4] evaluate values",
"[6.5] functions returning booleans"
],
"[7] Python Operators": [
"[7.1] intro to operators",
"[7.2] arithmetic operators",
"[7.3] assignment operators",
"[7.4] comparison operators",
"[7.5] identity operators",
"[7.6] membership operators"
],
"[8] Lists": [
"[8.1] intro to lists",
"[8.2] properties of lists",
"[8.3] accessing list items",
"[8.4] changing list items",
"[8.5] adding list items",
"[8.6] removing list items",
"[8.7] looping through lists",
"[8.8] list comprehension",
"[8.9] sorting lists",
"[8.10] copying lists",
"[8.11] joining lists",
"[8.12] list methods reference"
],
"[9] Tuples": [
"[9.1] intro to tuples",
"[9.2] properties of tuples",
"[9.3] accessing tuple items",
"[9.4] updating tuples",
"[9.5] unpacking tuples",
"[9.6] joining tuples",
"[9.7] tuple methods"
],
"[10] Sets": [
"[10.1] intro to sets",
"[10.2] set properties",
"[10.3] accessing set items",
"[10.4] add set items",
"[10.5] remove set items",
"[10.6] joining sets",
"[10.7] set methods"
],
"[11] Dictionaries": [
"[11.1] intro to dictionaries",
"[11.2] properties of dictionaries",
"[11.3] access dictionary items",
"[11.4] change dictionary items",
"[11.5] add dictionary items",
"[11.6] removing dictionary items",
"[11.7] looping through dictionaries",
"[11.8] copy dictionaries",
"[11.9] dictionary methods"
],
"[12] Conditional If Statement": [
"[12.1] intro to python conditionals",
"[12.2] the elif statement",
"[12.3] the else statement",
"[12.4] shorthands and ternary operators",
"[12.5] logical operators in conditionals",
"[12.6] nested if statements"
],
"[13] While Loops": [
"[13.1] intro to loops in python",
"[13.2] what are while loops",
"[13.3] break statement",
"[13.4] continue statement",
"[13.5] the while else statement",
"[13.6] the pass statement in while loops"
],
"[14] For Loops": [
"[14.1] intro to for loops",
"[14.2] break, continue, pass, and else statements in for loops",
"[14.3] looping through a sequence of numbers"
],
"[15] Functions": [
"[15.1] intro to functions",
"[15.2] function arguments",
"[15.3] advanced arguments",
"[15.4] the return statement",
"[15.5] recursion",
"[15.6] lambda functions"
],
"[16] Object-Oriented Python": [
"[16.1] intro to object-orients programming (OOP)",
"[16.2] classes & objects",
"[16.3] inheritance"
],
"[17] Iterators": [
"[17.1] what are iterators",
"[17.2] create an iterator",
"[17.3] stop an iterator"
],
"[18] Scope": [
"[18.1] what is scope",
"[18.2] variable naming in and out of blocks",
"[18.3] the global keyword"
],
"[19] Modules": [
"[19.1] what are modules",
"[19.2] use/import modules",
"[19.3] renaming modules",
"[19.4] built-in modules",
"[19.5] specified importing"
],
"[20] Dates": [
"[20.1] intro to dates",
"[20.2] create date objects",
"[20.3] the strftime() method"
],
"[21] Math": [
"[21.1] math in python",
"[21.2] math module"
],
"[22] Python JSON": [
"[22.1] intro to json",
"[22.2] json in python",
"[22.3] format json results"
],
"[23] PIP": [
"[23.1] intro to pip",
"[23.2] install packages",
"[23.3] uninstall packages",
"[23.4] list installed packages",
"[23.5] install and uninstall multiple packages"
],
"[24] Try Except": [
"[24.1] intro to try except",
"[24.2] specified error type exception",
"[24.3] try, except, else",
"[24.4] finally",
"[24.5] raise a custom error"
],
"[25] File Handling": [
"[25.1] intro to file handling",
"[25.2] read files",
"[25.3] write files",
"[25.4] create files",
"[25.5] delete files"
]
}
"""
# Intro [1]
# getting started [1.1]
"""
- To use python, you will need to install the language interpreter from
python's official site, and you will need an IDE, text editor to write
python.
- You might already have python installed in your device, to check if so,
run the following command in your cmd or terminal: python --version
- To run python files, run the following in your terminal: python filename.py
- You can test small amounts of python code in your terminal by using the python command: {
python
>>> print("Hello world from terminal!")
} or if that didn't work, you can use: {
py
>>> print("Hello world from terminal!")
}
- To exit the testing mode in the terminal, run the following command: exit()
"""
# syntax [1.2]
"""
- Python uses new line to complete a command, unlike other languages that use semi-colons
- Python uses indentation to contain a block scope, unlike other languages that use curly-brackets
- Indentation size doesn't matter, as long as all the code from the same block is on the same level
"""
def first_function(): # never mind about this def thingy, you will know about it later, this is just for demonstration
lang = "Python"
print("This is my first code in " + lang + "!")
# notice how end of command was just a new line rather than semi-colons
# notice how the block scope of the function is just defined using indentation
first_function()
# comments [1.3]
"""
- Commented code is ignored when run.
- Comments are used to add documentation to your code, explain a code, or comment out a code
temporarily or for testing purposes.
- In python, there are two types of comments: {
1- Single line comments using hashtags
2- Multi-line comments using triple quotes
}
"""
# this is a single line comment
eee = 5 # this is a single line comment after some uncommented code
""" this is a multi-line comment """
"""
Multi-line comment actually being multi-line
would look like this
"""
# print statement [1.4]
"""
- In python, you can print values into the screen
- To print values into the screen, use the print keyword
"""
print("Hello world! this my first print statement")
# input [1.5]
"""
- One thing to know how to do in python, is to get user input
- In python 2.7, we were able to take the user input by using the raw_input() method, but forget about that now
- In modern python (python 3.6), we can take the user input by using the input() method
"""
def take_user_input(): # never mind about this line for now, its just to contain the input statement
user_name = input("Enter your name")
print(user_name) # this prints whatever the user entered as an input
# Variables [2]
# intro to variables [2.1]
"""
- Variables in programming are used to store data values.
- Unlike other languages, python doesn't have a keyword for declaring variables,
you declare variables by just defining the name, then = sign, then the value.
"""
# defining variables
my_first_variable = "This is my first variable" # defining a variable storing a string value
# a string is a text value, will be explained in details in a later lesson
num_var = 2022 # defining a variable named "num_var" and setting it's value to be a number value (2022)
# casting [2.2]
# you can specify the data type of a variable using casting
name = str("Swordax") # specifying that variable (name) value will be a string using str()
age = int(2022) # specifying that variable (age) value will be an integer using int()
weight = float(1.2) # specifying that variable (weight) value will be a float using float()
# there are more data types, those will be listed for now
# an integer is a whole number (no decimals), float numbers are numbers with decimals
# if you do float(1) the value will be 1.0
# overwriting variables [2.3]
# you can overwrite variables original value and set a new value to it
overwriting_variables = "Original Variable Value"
print(overwriting_variables) # this will print: "Original Variable Value" as it's original value defined above
overwriting_variables = "Overwritten Variable Value" # we can overwrite variables values
print(overwriting_variables) # this will print: "Overwritten Variable Value"
# get variable value data type [2.4]
string_var = "This is a string value"
integer_var = 100
float_var = 3.14
print(type(string_var)) # this will print: <class 'str'> which means it's a string
print(type(integer_var)) # this will print: <class 'int'> which means it's an integer
print(type(float_var)) # this will print: <class 'float'> which means it's a float
# string variable declaration [2.5]
"""
- When you define a string variable value, you have to contain it inside quotes '' or ""
- You can use single OR double quotes when defining the value of a string variable, choice is yours!
- If you want to contain quotes inside your text, use the other type of quotes, example: {
"My name is 'Swordax' and I am a programmer"
'My name is "Swordax" and I am a programmer'
}
"""
single_quotes = 'This text is contained inside single quotes'
double_quotes = "This text is contained inside double quotes"
nested_quotes_1 = "This text contains 'single' quotes"
nested_quotes_2 = 'This text contains "double" quotes'
# variable naming rules [2.6]
"""
- When naming variables, there are rules you need to follow: {
1- variable name must start with a letter or an underscore
2- variable name CANNOT start with a number
3- variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, _)
4- variable names are case-sensitive, so (age, AGE, Age) are three different variables
}
"""
varexample = "valid"
VAREXAMPLE = "valid"
VarExample = "valid"
varExample = "valid"
var_example = "valid"
var0example = "valid"
# multi-name variable naming style [2.7]
"""
You can name a variable whatever you want (as long as the name follows the rules mentioned in lesson 2.6),
but it's a common good practice to name it using one of the popular naming styles, just as a good habit.
"""
camelCase = "variable named using the camel case naming style"
PascalCase = "variable named using the pascal case naming style"
snake_case = "variable named using the snake case naming style"
# assigning multiple values to variables [2.8]
a, b, c = "a value", "b value", "c value" # defining and assigning three variables at a time
x = y = z = "single value for x, y, and z" # assigning the same value for 3 variables at a time
fruits = ["apple", "banana", "cherry"] # declaring a list (you will learn about lists more in later lessons)
q, w, e = fruits # unpacking the list into separate separate variables
# outputting variables [2.9]
my_name = "Swordax"
print("My name is " + my_name) # combining text with a variable
sentence = "My name is "
print(sentence + my_name) # printing two variables (combining them)
his_name = "Swordy Man"
her_name = "Swordy Woman"
their_names = his_name + " " + her_name # notice combining variables and texts in a single variable
print(their_names) # printing the variable that combines the other variables
"""
As you can see in the previous examples, using "+" between string values concatenates and joins them,
but when using it between number values, it will actually operate addition on them.
"""
one = 1
two = 2
print(one + two) # this will print 3
_one = "1"
_two = "2"
print(_one + _two) # this will print "12"
"""
- If you try to join a string value with a number value, you will get an error, so the following: {
text = "Hello world!"
number = 12
print(text + number)
} will result in an error
"""
# variables scope [2.10]
"""
- Variables are accessible only inside their scope. Almost all the variables that we have created
in the previous lessons (excluding lesson 1.2) are global variables, because they all were created
and declared on the top level scope in the code.
- Global Variables: a variable that is accessible everywhere in the code.
- Scope: a scope can be defined as the current block of code and it's whole content of code and blocks.
- Function Scope: the scope of a function code block (functions will be explained in details in later lessons)
"""
global_variable = "this can be accessible everywhere in the code"
def scope_demo():
print(global_variable) # this would work because global_variable is a global variable
local_variable = "this variable is only accessible inside the scope of scope_demo() function"
if True:
print(global_variable) # this would work
print(local_variable) # this would work
# the previous line would work because the local_variable is still inside the scope of scope_demo() function
scope_demo()
# print(local_variable) <- this code would make an error as local_variable is not in the scope of it's function
print(global_variable) # this would work
"""
You can overwrite a global variable inside a function only while reserving its original value outside the function
"""
global_var = "Original"
def overwriting_demo():
global_var = "Overwritten"
print(global_var) # prints: "Overwritten"
overwriting_demo()
print(global_var) # prints: "Original" notice how it wasn't overwritten outside the function scope
"""
You can make a local variable inside a function global by using the "global" keyword
"""
def scope_demo_2():
global global_keyword
global_keyword = "Hello world!"
scope_demo_2()
print(global_keyword)
# ^ this would work even though the global_keyword variable was defined inside a function because of the global keyword
"""
If you want to overwrite a global variable inside a function, you will need to use the global keyword
"""
global_variable_2 = "Hello world!"
def scope_demo_3():
global global_variable_2
print(global_variable_2) # prints: "Hello world!"
global_variable_2 = "Hello universe!"
print(global_variable_2) # prints: "Hello universe!"
print(global_variable_2) # prints: "Hello world!"
scope_demo_3()
print(global_variable_2) # prints: "Hello universe!"
# Data Types [3]
# intro to data types [3.1]
"""
- Data types in programming can be defined as the type of data ( silly definition isn't it :/ )
- Variables can store data from different types, and different types can do different things
- There are many built-in data types in python, and this is a list of them in categories: {
Text Type: str
Number Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
}
- As mentioned in previous lessons, you can get the data type of a value using type() built-in function: {
string = "Text"
print(type(string)) # this will print the data type of string variable
}
"""
# data types in real code [3.2]
string_type = "str"
integer_type = 4
float_type = 12.4
complex_type = 1j
list_type = ["Swordax", "Swordy", "Sword"]
tuple_type = ("Swordax", "Swordy", "Sword")
range_type = range(4)
dict_type = {
name: "Swordax",
age: 2022
}
set_type = {"Swordax", "Swordy", "Sword"}
frozenset_type = frozenset({"Swordax", "Swordy", "Sword"})
bool_type = True
bytes_type = b"Swordax"
bytearray_type = bytearray(4)
memoryview_type = memoryview(bytes(4))
# setting specific data type (casting) [3.3]
"""
- When creating a variable, you can specify what data type you want it to be by using a constructor function.
- Data type constructor functions come with the exact same naming of the data types listed in lesson 3.1
- Examples to build your understanding around: {
_string = str("String data type")
_integer = int(4)
_float = float(4.2)
_complex = complex(1j)
_list = list(("Swordax", "Swordy", "Sword"))
_tuple = tuple(("Swordax", "Swordy", "Sword"))
_range = range(6)
_dict = dict(name = "Swordax", age = 2022)
_set = set(("Swordax", "Swordy", "Sword"))
_frozenset = frozenset(("Swordax", "Swordy", "Sword"))
_bool = bool(4)
_bytes = bytes(4)
_bytearray = bytearray(4)
_memoryview = memoryview(bytes(4))
}
"""
# Numbers [4]
# numeric data types [4.1]
"""
- Python contains three numeric data types: {
- int: integers, whole numbers, positive or negative, without decimals, of unlimited length.
- float: floating point numbers, positive or negative, containing one or more decimals.
- complex: complex numbers, written with a "j" character as the imaginary part.
}
"""
# int
int_1 = 100
int_2 = -123
int_3 = 8375829075983
# float
float_1 = 1.12
float_2 = -42.24323
float_3 = 1.0
float_4 = 29e4
float_5 = -234E39
# complex
complex_1 = 5j
complex_2 = -5j
complex_3 = 2+6j
# numeric type conversion [4.2]
"""
You can convert between data types using the int(), float(), complex() built-in methods
"""
print(int(float_1)) # prints: 1
print(float(int_1)) # prints: 100.0
print(complex(float_3)) # prints: (1+0j)
# NOTE: you cannot convert complex numbers into other numeric data types
# random numbers [4.3]
"""
- You can generate a random number in python!
- Python does not have a function that generates random numbers, but it has a built-in
modules that does that for us, and its called "random"
- To use modules in python, you will first have to import them.
- Usually you would have to install external modules, but since the random module
is built in the language itself, you wont have to install anything, just directly import the module.
"""
import random
random_number = random.randrange(1, 10) # this will generate a random number between 1 and 9 (10 is excluded)
print(random_number) # this will print the generated random number
# Strings [5]
# basic strings [5.1]
"""
- In python, strings are text values, they are surrounded by quotes, either single or double.
- "Hello world!" is the same as 'Hello world!'
"""
string_ex_1 = "This is a string"
string_ex_2 = 'This is another string'
string_ex_3 = """
You can create multi-line string variables by using triple double quotes,
or triple single quotes, as easy as that!
"""
string_ex_4 = '''
Another example of multi-line string variables,
but this time created using triple single quotes
'''
# NOTE: in multi-line strings, the breaks in the line are included in the outputs
# get a specific character in a string [5.2]
"""
- you can get a specific character inside your string using square brackets
- if your familiar with other programming languages, you should be familiar with this information. In
programming, we don't start counting from 1, but we start counting from 0, get used to that!
- you get the nth-character in the string by counting from 0, so the 0th character is the 1st character.. etc..
"""
string_ex_5 = "Hello world!"
print(string_ex_5[0]) # prints: "H"
print(string_ex_5[1]) # prints: "e"
# etc..
# the len() method [5.3]
# you can get the length of a string (number of characters in a string) by using the len() method
print(len(string_ex_5)) # prints: 12 (since the number of characters inside string_ex_5 is 12 characters)
# a trick that can help you get the last character in a string:
string_ex_6 = "The last character here is Z"
print(string_ex_6[len(string_ex_6) - 1])
"""
Explanation: {
- we had to get the last character in the string, so we got the nth (string length - 1) character.
- the -1 is because as you know, we start counting from 0 and not from 1
}
"""
# the in keyword [5.4]
"""
- we can check if a certain character or phrase is present inside a string by using the "in" keyword
- the result of this check will be a boolean value, which is either True or False
- note that the check is case sensitive, so you should make sure to get the letter casing right
"""
string_ex_7 = "Swordax"
print("S" in string_ex_7) # prints: True (since character "S" is present inside the string "Swordax")
print("s" in string_ex_7) # prints: False (since character "s" is not present inside the string "Swordax")
print("dax" in string_ex_7) # prints: True (since the phrase "dax" is present inside the string "Swordax")
print("da x" in string_ex_7) # prints: False (since the phrase "da x" is not present inside the string "Swordax")
# you can check if character or phrase is NOT present in a string by adding the "not" keyword (logical operator)
print("ZZZ" not in string_ex_7) # prints: True (as "ZZZ" is not present in "Swordax")
# etc..
# slicing strings [5.5]
"""
- sometimes you might need to slice a string (crop a string) to get a specific part of it
- in python, its very easy to slice a string
"""
my_sentence = "Hello world!"
hello_word = my_sentence[0:5] # this contains "Hello" which is from character 0 to character 4 (5 excluded)
world_word = my_sentence[6:11] # this contains "world" which is from character 6 to character 10 (11 excluded)
exclamation = my_sentence[11:12] # this contains "!" which is from character 11 to character 12 (12 excluded)
print(hello_word + " " + world_word + exclamation) # prints: "Hello world!"
# slice from start by leaving the first index empty
print(my_sentence[:5]) # prints: "Hello"
# slice to the end by leaving the last index empty
print(my_sentence[6:]) # prints: "world!"
# negative indexing (cut from the end of the string backwardly)
print(my_sentence[-5:-2]) # prints: "orl" (from index -5 backwardly to index -2 backwardly (excluded))
# string modification [5.6]
"""
- Python has a set of built-in methods and functions that can be used to modify strings
"""
lowercased_str = "hello"
uppercased_str = "HELLO"
padded_str = " Hello "
test_str = "My name is Zwordax!"
names_str = "Swordax, Vazox, Sword"
print(lowercased_str.upper()) # prints an upper-cased version of the string
print(uppercased_str.lower()) # prints a lower-cased version of the string
print(padded_str.strip()) # prints a stripped/trimmed version of the string (removes white spaces around the string)
print(test_str.replace("Z", "S")) # prints a version of the string where all "Z" characters are replaced with "S"
# notice that the replacing is case-sensitive, so the previous example will only replace the "S" letters not the "s"
print(names_str.split(",")) # prints a list (array), breaks and separates at commas
# the split() method changes the string into a list and separates words depending on the passed separator
# string format() method [5.7]
"""
- The format() method allows us to insert dynamic values into a string, and concatenate strings.
- In the main string, we will use curly-brackets to define where the inserting should take place.
- In the format() function, we should pass into the parenthesis the values we want to insert.
- Make sure the number of curly-brackets is euil to the number of items inserted in the format() function.
- Note: as you know, we normally cannot concatenate/join strings and numbers together without convering them,
but when using the format() method, we can do that!
"""
template = "My name is {}, I am {} years old, I am from {}"
final_txt = template.format("Swordax", 2022, "CLASSIFIED")
print(final_txt) # prints: "My name is Swordax, I am 2022 years old, I am from CLASSIFIED"
# you can always do it differently! for example, you can pass variables instead of direct strings
_name = "Swordax"
_age = 2022
_nationality = "CLASSIFIED"
print(template.format(_name, _age, _nationality)) # this should print the same result as the previous example
# you can change the order of the inserted items by passing indexing into the curly-brackets in the template
template_2 = "My name is {2}, I am {0} years old, I am from {1}"
print(template_2.format(2022, "CLASSIFIED", "Swordax")) # this should print the same result as previous examples
# escape characters [5.8]
"""
- Sometimes you might need to use illegal characters in a string that you normally can't use, well, you
can do that using the escape character (back-slash) + (escaped character)
"""
txt = "My name is \"Swordax\""
"""
- As you can see in the previous example, we created a string with double quotes, and we had to use
double quotes inside the string. doing that without using the escape characters will cause errors because
python won't know which quotes are closing the string and which are inside the string.
- You can use double quotes inside double-quoted strings using the escape character (back-slash) + (double quote).
-The escape character allows you to use illegal characters inside strings.
- In the previous example, we could have just used single quotes to include the string, but its just
an example, and you will sometimes be in situations where you will really need the escape character.
"""
"""
- Escape Characters: {
\' : escape single quotes
\" : escape double quotes
\\ : escape backslashes
\n : break to a new line
\r : carriage return
\t : tab
\b : backspace
\f : form feed
\ooo : octal value
\xhh : hex value
}
"""
# string methods [5.9]
"""
- We have previously seen a number of string methods in the previous lessons, but here is a
bigger list of them.
"""
s = "this is a string"
# methods
s.capitalize() # converts the first character to upper case
s.casefold() # converts string to lower case
s.center() # returns a centered string (length, character)
s.count() # returns the number of times a specified value occurs in a string (word)
s.encode() # returns an encoded version of the string (encoding)
s.endswith() # returns true if the string ends with the specified value (value)
s.expandtabs() # sets the tab size of the string (amount)
s.find() # searches the string for a specified value and returns the position of where it was found (word to find)
s.format() # formats specified values in a string (words)
s.format_map() # formats specified values in a string
s.index() # searches the string for a specified value and returns the position of where it was found (word to find)
s.isalnum() # returns true if all characters in the string are alphanumeric
s.isalpha() # returns true if all characters in the string are in the alphabet
s.isdecimal() # returns true if all characters in the string are decimals
s.isdigit() # returns true if all characters in the string are digits
s.isidentifier() # returns true if the string is an identifier
s.islower() # returns true if all characters in the string are lower case
s.isnumeric() # returns true if all the characters in the string are numeric
s.isprintable() # returns true if all characters in the string are printable
s.isspace() # returns true if all characters in the string are whitespaces
s.istitle() # returns true if the string follows the rules of a title
s.isupper() # returns true if all characters in the string are upper case
s.join() # joins the elements of an iterable to the end of the string (list)
s.ljust() # returns a left justified version of the string (length, character)
s.lower() # converts a string into lower case
s.lstrip() # returns a left trim version of the string
s.maketrans() # returns a translation table to be used in translations
s.partition() # returns a tuple where the string is parted into three parts (word)
s.replace() # returns a string where a specified value is replaced wth a specified value (replace, replace with)
s.rfind() # searches the string for a specified value and returns the last position of where it was found (word to find)
s.rindex() # searches the string for a specified value and returns the last position of where it was found (word to find)
s.rpartition() # returns a tuple where the string is parted into three parts (word)
s.rsplit() # splits the string at the specified separator, and returns a list (separator, maxsplit)
s.rstrip() # returns a right trim version of the string
s.split() # splits the string at the specified separator, and returns a list (separator)
s.splitlines() # splits the string at line breaks and returns a list (should line break be included, default false)
s.startswith() # returns true of the string starts with the specified value (value)
s.strip() # returns a trimmed version of the string
s.swapcase() # swaps cases, lower case becomes upper case and vice versa
s.title() # converts the first character of each word to upper case
s.translate() # returns a translated string
s.upper() # converts a string into upper case
s.zfill() # fills the string with a specified number of 0 values at the beginning (number)
# Booleans [6]
# intro to booleans [6.1]
"""
- A boolean is a data type in programming languages
- A boolean can have 2 possible values only, True or False
- The value of a boolean is not contained inside quotes, its dealt with as a keyword
- Booleans have a constructor function of bool()
"""
# evaluating expressions [6.2]
print(12 > 4) # prints: True (because 12 is more than 4)
print(12 == 4) # prints: False (because 12 is not equal to 4)
print(12 < 4) # prints: False (because 12 is not less than 4)
# don't worry about the comparison operators now, they will be discussed in details in later lessons
# booleans in conditional statements [6.3]
v_one = 100
v_two = 200
if v_one > v_two: # the condition in the if statement is either True or False, which decides if the code runs or not
print("Value one is more than value two") # the if condition evaluated to False, so the print statement wont run
if True: # we manually passed a static True, so the if statement will always run
print("Value is true")
if False: # we manually passed a static False, so the if statement will never run
print("Value is true")
# evaluate values [6.4]
# the bool() function allows you to evaluate any value, and give a True or False in return
print(bool("Hello world")) # prints True
print(bool(2022)) # prints True
bool_one = "Hello world"
bool_two = 2022
print(bool(bool_one)) # prints True
print(bool(bool_two)) # prints False
"""
- Almost any value is evaluated as True as it exists
- Empty strings evaluate as False
- All numbers evaluate as True, even negative numbers, except for 0 which evaluates as False
- Lists, dictionaries, tuples, and sets, all evaluate as True, except for empty ones
"""
# all the following evaluates to False
print(bool({}))
print(bool([]))
print(bool(()))
print(bool(""))
print(bool(0))
print(False)
print(None) # this is similar to "null" in JS, it basically says that the value is None, it evaluates to False
# functions returning booleans [6.5]
"""
- Functions can return booleans, this could be useful when using a function to determine if something is True or not
"""
def booleanFunction_T():
return True
def booleanFunction_F():
return False
# you can then use this function in conditional statements
if booleanFunction_T(): # since this function returns a boolean, its a valid condition in if statements
print("that is true!")
else:
prit("that is false!")
# don't worry about if statements and functions for now, they are just for demo. will be explained in later lessons
# Python Operators [7]
# intro to operators [7.1]
"""
- Operators are used to perform operations on values and variables
- There are many kinds of operators, can be listed as: {
* Arithmetic operators
* Assignment operators
* Comparison operators
* Logical operators
* Identity operators
* Membership operators
* Bitwise operators
}
"""
# a simple example of an operator we have used alot in the past lessons, the + operator to add numbers together
print(12 + 4) # performs a mathematical operation and prints 16
# arithmetic operators [7.2]
"""
- Arithmetic operators are used with numeric values to perform common mathematical operations: {
+ : addition operator : used to add values together (used also for string concatenation)
- : subtraction operator : used to subtract values from each other
* : multiplication operator : used to multiply values with each other
/ : division operator : used to divide values from each other
% : modulus operator
** : exponential operator
// : floor division operator
}
"""
# popular operators in use
print(12 + 4) # addition operator
print(12 - 4) # subtraction operator
print(12 * 4) # multiplication operator
print(12 / 4) # division operator
# assignment operators [7.3]
"""
- Assignment operators are used to assign values to variables: {
= : equal sign : used to assign a value to a variable
+= : increment operator : used to increment a variable value by a specific number
-= : decrement operator : used to decrement a variable value by a specific number
*= : multiply by operator : used to multiply a variable by a specific number
/= : divide by operator : used to divide a variable by a specific number
}
note: there are more operators that are not mentioned as they aren't that popular and widely used
"""
val = 1 # variable assigned with value of 1
val += 1 # incremented by 1
val -= 1 # decremented by 1
val *= 1 # multiplied by 1
val /= 1 # divided by 1
# comparison operators [7.4]
"""
- Logical operators are used to combine conditional statements: {
and : returns True if both statements are True
or : returns True if one of the statements is True
not : reverses the result of the condition, so returns False if True, vice versa
}
"""
if 1 == 1 and 2 == 2: # can be compared to && in JavaScript
print("both conditions are true")
if 1 == 1 or 2 == 1: # can be cmopared to || in JavaScript
print("one of the conditions is true")
if not 1 == 2: # can be compared to ! in JavaScript
print("the condition was not true but it was reversed so evaluated as true")
# identity operators [7.5]
"""
- Identity operators are used to compare objects, not for the equality of their values, but if
they are actually the same object with the same memory location: {
is : returns True if both variables are the same object
is not : returns True if both variables are NOT the same object
}
"""
first_object = ["Hello", "World"]
second_object = ["Hello", "World"]
third_object = first_object
print(first_object is third_object) # prints True
print(first_object is second_object) # prints False
print(first_object is not second_object) # prints True
print(first_object == second_object) # prints True
# membership operators [7.6]
"""
- Membership operators are used to test if a sequence is presented in an object: {
in : returns True if a sequence with the specified value is present in the object
not in : returns True is a sequence with the specified value is NOT present in the object
}
"""
food = ["Apple", "Banana", "Tomato"]
print("Apple" in food) # prints True
print("Humus" in food) # prints False
print("Pineapple" not in food) # prints True
# NOTE, the bitwise operators lesson will be skipped for now
# Lists [8]
# intro to lists [8.1]
"""
- Lists are used to store multiple items in a single variable
- Lists can be compared to arrays in JavaScript
- There are 4 data-types that can store collections of data in python, lists are one of them, others
are tuples, sets, and dictionaries, each with its different qualities
- Lists are created using square brackets
"""
# creating a simple list
first_list = ["red", "green", "blue"] # created a list that contains three items
print(first_list) # prints ['red', 'green', 'blue']
# finding the length of a list (number of items in a list)
my_list = ["one", "two", "three", "four"] # a list with four items
print(len(my_list)) # the len() function can be used to find the length of a list, or the number of items inside it
# lists can contain any data-type, it can even contain other lists
list_of_names = ["Python", "JavaScript", "PHP", "Java"]
list_of_numbers = [12, 4, 2022, 0, 999]
list_of_bools = [True, False, False, True]
list_of_mixed = ["Heya!", 2022, 3.14, True]
nested_list = [["Python", 1991], ["JavaScript", 1995], ["PHP", 1994]] # even more nesting is possible
# printing list type
print(type(my_list)) # this will print <class 'list'> as we learned in previous lessons
# the list() constructor
"""
Lists can be created using the list() constructing function
"""
constructed_list = list(("House", "School", "Hospital")) # notice how we used parenthesis and not square brackets
# properties of lists [8.2]
"""
- Each collection type has its own properties, the list properties are: {
1- ordered: they have a defined order that will not change unless we change it, lists are indexed
2- changeable: list items can be added, removed, or modified after creating a list
3- allows duplicate values: since lists are indexed, they can have items with identical values
}
"""
# ordered
list_1 = ["Apple", "Banana", "Watermelon"] # "Apple" is always the first item, "Watermelon" is always the last
# changeable as in later lessons we will learn how to add, remove, or modify list items in a list
# allows duplicate values
list_2 = ["Apple", "Banana", "Apple", "Watermelon", "Banana", "Apple"] # this is a valid list
# accessing list items [8.3]
"""
- As we learned before, lists are ordered and indexed
- Each list item has an index that you can use to access the item and get it or change it
- Remember how we accessed string characters using square brackets, same applies with lists but this time
we will be accessing items instead of characters
- Remember, in programming, counting indexes starts from 0 and not from 1
"""
access_list = ["Item one", "Item two", "Item three"]
print(access_list[0]) # prints the first list item "Item one"
print(access_list[1]) # prints the second list item "Item two"
print(access_list[2]) # prints the third list item "Item three"
# accessing items backwardly (negative indexing)
print(access_list[-1]) # prints the last item
print(access_list[-2]) # prints the second last item
# range of indexes (getting a group of list items)
long_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(long_list[2:5]) # gets and prints a list of items from item of index 2 to item of index 4 (5 is excluded)
print(long_list[:4]) # by leaving out the first index, the range will start at the first item
print(long_list[2:]) # by leaving out the last index, the range will end at the last item
# you can use negative values to start the cut from the end of the list (backwardly)
print(long_list[-4:-1]) # this is a valid example
# you can use the "in" keyword to check if an item exists in a list
print("apple" in long_list) # this prints True