-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpython-basics.html
1441 lines (1340 loc) · 51.1 KB
/
python-basics.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=yes"
/>
<title>python-basics</title>
<style type="text/css">
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
span.underline {
text-decoration: underline;
}
div.column {
display: inline-block;
vertical-align: top;
width: 50%;
}
</style>
</head>
<body>
<h1 id="notes"><strong>Notes</strong></h1>
<h2 id="basics"><strong>Basics</strong></h2>
<ul>
<li>
<p>
<strong>PEP8</strong> : Python Enhancement Proposals, style-guide for
Python.
</p>
</li>
<li>
<p><code>print</code> is the equivalent of <code>console.log</code>.</p>
</li>
<li>
<p><code>#</code> is used to make comments in your code.</p>
<p>
def foo(): """ The foo function does many amazing things that you
should not question. Just accept that it exists and use it with
caution. """ secretThing()
</p>
</li>
<li>
<p>
Python has a built in help function that let’s you see a description
of the source code without having to navigate to it.
</p>
</li>
</ul>
<hr />
<h2 id="numbers"><strong>Numbers</strong></h2>
<ul>
<li>
<p>Python has three types of numbers:</p>
<ul>
<li>
<p><strong>Integer</strong></p>
<ul>
<li>Positive and Negative Counting Numbers.</li>
<li>No Decimal Point</li>
<li>
<p>
Created by a literal non-decimal pt number or with the
<code>int()</code> constructor.
</p>
<p>
print(3) # => 3 print(int(19)) # => 19 print(int()) #
=> 0
</p>
</li>
</ul>
<blockquote>
<p>Boolean is a subtype of integer in Python.</p>
</blockquote>
</li>
<li>
<p><strong>Floating Point Number</strong></p>
<ul>
<li>
<p>Decimal Numbers.</p>
<p>
print(2.24) # => 2.24 print(2.) # => 2.0 print(float())
# => 0.0 print(27e-5) # => 0.00027
</p>
</li>
</ul>
</li>
<li>
<p><strong>Complex Numbers</strong></p>
<ul>
<li>Consist of a real part and imaginary part.</li>
<li>
<p>
The <code>i</code> is switched to a <code>j</code> in
programming.
</p>
<p>
print(7j) # => 7j print(5.1+7.7j)) # => 5.1+7.7j
print(complex(3, 5)) # => 3+5j print(complex(17)) # =>
17+0j print(complex()) # => 0j
</p>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p>
<strong>Type Casting</strong> : The process of converting one number
to another.
</p>
<h1 id="using-float">Using Float</h1>
<p>print(17) # => 17 print(float(17)) # => 17.0</p>
<h1 id="using-int">Using Int</h1>
<p>print(17.0) # => 17.0 print(int(17.0)) # => 17</p>
<h1 id="using-str">Using Str</h1>
<p>print(str(17.0) + ’ and ’ + str(17)) # => 17.0 and 17</p>
</li>
<li>
<p>
The arithmetic operators are the same between JS and Python, with two
additions:
</p>
<ul>
<li>“**” : Double asterisk for exponent.</li>
<li>“//” : Integer Division.</li>
</ul>
</li>
<li><p>There are no spaces between math operations in Python.</p></li>
<li>
<p>
Integer Division gives the other part of the number from Module; it is
a way to do round down numbers replacing <code>Math.floor()</code> in
JS.
</p>
</li>
<li>
There are no <code>++</code> and <code>--</code> in Python, the only
shorthand operators are:
</li>
<li>
<figure>
<img
src="https://i.gyazo.com/745b12d4b84304462e53a69d8492c58d.png"
alt="pic"
/>
<figcaption>pic</figcaption>
</figure>
</li>
</ul>
<hr />
<h2 id="strings"><strong>Strings</strong></h2>
<ul>
<li><p>Python uses both single and double quotes.</p></li>
<li>
<p>
You can escape strings like so
<code>'Jodi asked, "What\'s up, Sam?"'</code>
</p>
</li>
<li>
<p>Multiline strings use triple quotes.</p>
<p>
print(’‘’My instructions are very long so to make them more readable
in the code I am putting them on more than one line. I can even
include “quotes” of any kind because they won’t get confused with the
end of the string!’’’)
</p>
</li>
<li>
<p>
Use the <code>len()</code> function to get the length of a string.
</p>
<pre><code>print(len("Spaghetti")) # => 9</code></pre>
</li>
<li>Python uses <code>zero-based indexing</code></li>
<li>
<p>Python allows negative indexing (thank god!)</p>
<pre><code>print("Spaghetti"[-1]) # => i
print("Spaghetti"[-4]) # => e</code></pre>
</li>
<li>
<p>Python let’s you use ranges</p>
<pre><code>print("Spaghetti"[1:4]) # => pag
print("Spaghetti"[4:-1]) # => hett
print("Spaghetti"[4:4]) # => (empty string)</code></pre>
<ul>
<li>
The end range is exclusive just like <code>slice</code> in JS.
</li>
</ul>
<h1
id="shortcut-to-get-from-the-beginning-of-a-string-to-a-certain-index."
>
Shortcut to get from the beginning of a string to a certain index.
</h1>
<p>
print(“Spaghetti”[:4]) # => Spag print(“Spaghetti”[:-1]) # =>
Spaghett
</p>
<h1 id="shortcut-to-get-from-a-certain-index-to-the-end-of-a-string.">
Shortcut to get from a certain index to the end of a string.
</h1>
<p>
print(“Spaghetti”[1:]) # => paghetti print(“Spaghetti”[-4:]) #
=> etti
</p>
</li>
<li>
<p>
The <code>index</code> string function is the equiv. of
<code>indexOf()</code> in JS
</p>
<p>
print(“Spaghetti”.index(“h”)) # => 4 print(“Spaghetti”.index(“t”))
# => 6
</p>
</li>
<li>
<p>
The <code>count</code> function finds out how many times a substring
appears in a string.
</p>
<p>
print(“Spaghetti”.count(“h”)) # => 1 print(“Spaghetti”.count(“t”))
# => 2 print(“Spaghetti”.count(“s”)) # => 0 print(’‘’We choose
to go to the moon in this decade and do the other things, not because
they are easy, but because they are hard, because that goal will serve
to organize and measure the best of our energies and skills, because
that challenge is one that we are willing to accept, one we are
unwilling to postpone, and one which we intend to win, and the others,
too.’’‘.count(’the’)) # => 4
</p>
</li>
<li>
<p>
You can use <code>+</code> to concatenate strings, just like in JS.
</p>
</li>
<li>
<p>You can also use “*” to repeat strings or multiply strings.</p>
</li>
<li>
<p>
Use the <code>format()</code> function to use placeholders in a string
to input values later on.
</p>
<p>
first_name = “Billy” last_name = “Bob” print(‘Your name is {0}
{1}’.format(first_name, last_name)) # => Your name is Billy Bob
</p>
</li>
<li>
<p>
Shorthand way to use format function is:
<code>print(f'Your name is {first_name} {last_name}')</code>
</p>
</li>
<li>
<p>Some useful string methods.</p>
<ul>
<li>
Note that in JS <code>join</code> is used on an Array, in Python it
is used on String.
<img
src="https://i.gyazo.com/ed5094aa444e325b59ec3a11393b60f2.png"
alt="pic"
/>
</li>
</ul>
</li>
<li>
<p>
There are also many handy testing methods.
<img
src="https://i.gyazo.com/af6244c64c06827fb19ac9cd86a75d17.png"
alt="pic"
/>
</p>
</li>
</ul>
<hr />
<h2 id="variables-and-expressions">
<strong>Variables and Expressions</strong>
</h2>
<ul>
<li>
<p>
<strong>Duck-Typing</strong> : Programming Style which avoids checking
an object’s type to figure out what it can do.
</p>
<ul>
<li>Duck Typing is the fundamental approach of Python.</li>
</ul>
</li>
<li>
<p>Assignment of a value automatically declares.</p>
<p>a = 7 b = ‘Marbles’ print(a) # => 7 print(b) # => Marbles</p>
</li>
<li>
<p>
You can chain variable assignments to give multiple var names the same
value.
</p>
<ul>
<li>Use with caution as this is highly unreadable</li>
</ul>
<p>
count = max = min = 0 print(count) # => 0 print(max) # => 0
print(min) # => 0
</p>
</li>
<li>
<p>The value and type of a variable can be re-assigned at any time.</p>
<p>
a = 17 print(a) # => 17 a = ‘seventeen’ print(a) # => seventeen
</p>
</li>
<li>
<p>
<code>NaN</code> does not exist in Python, but you can ‘create’ it
like so: <code>print(float("nan"))</code>
</p>
</li>
<li>
Python replaces <code>null</code> with <code>none</code>.
<ul>
<li>
<code>none</code> is an object and can be directly assigned to a
variable.
</li>
<li>
Using none is a convenient way to check to see why an action may not
be operating correctly in your program.
</li>
</ul>
</li>
</ul>
<hr />
<h2 id="boolean-data-type"><strong>Boolean Data Type</strong></h2>
<ul>
<li>
<p>
One of the biggest benefits of Python is that it reads more like
English than JS does.
<img
src="https://i.gyazo.com/3d9fb881df9245a42024aae4ee38a1c5.png"
alt="pic"
/>
</p>
<h1 id="logical-and">Logical AND</h1>
<p>
print(True and True) # => True print(True and False) # => False
print(False and False) # => False
</p>
<h1 id="logical-or">Logical OR</h1>
<p>
print(True or True) # => True print(True or False) # => True
print(False or False) # => False
</p>
<h1 id="logical-not">Logical NOT</h1>
<p>
print(not True) # => False print(not False and True) # => True
print(not True or False) # => False
</p>
</li>
<li>
<p>
By default, Python considers an object to be true UNLESS it is one of
the following:
</p>
<ul>
<li>Constant <code>None</code> or <code>False</code></li>
<li>Zero of any numeric type.</li>
<li>Empty Sequence or Collection.</li>
</ul>
</li>
<li>
<p><code>True</code> and <code>False</code> must be capitalized</p>
</li>
</ul>
<hr />
<h2 id="comparison-operators"><strong>Comparison Operators</strong></h2>
<ul>
<li><p>Python uses all the same equality operators as JS.</p></li>
<li>
<p>In Python, equality operators are processed from left to right.</p>
</li>
<li>
<p>Logical operators are processed in this order:</p>
<ol type="1">
<li><strong>NOT</strong></li>
<li><strong>AND</strong></li>
<li><strong>OR</strong></li>
</ol>
</li>
<li>
<p>
Just like in JS, you can use <code>parentheses</code> to change the
inherent order of operations.
</p>
</li>
<li>
<p>
<strong>Short Circuit</strong> : Stopping a program when a
<code>true</code> or <code>false</code> has been reached.
<img
src="https://i.gyazo.com/ccbe5511757813a61e3833d13c43fd8b.png"
alt="pic"
/>
</p>
</li>
</ul>
<hr />
<h2 id="identity-vs-equality"><strong>Identity vs Equality</strong></h2>
<pre><code>print (2 == '2') # => False
print (2 is '2') # => False
print ("2" == '2') # => True
print ("2" is '2') # => True
# There is a distinction between the number types.
print (2 == 2.0) # => True
print (2 is 2.0) # => False</code></pre>
<ul>
<li>
In the Python community it is better to use <code>is</code> and
<code>is not</code> over <code>==</code> or <code>!=</code>
</li>
</ul>
<hr />
<h2 id="if-statements"><strong>If Statements</strong></h2>
<pre><code>if name == 'Monica':
print('Hi, Monica.')
if name == 'Monica':
print('Hi, Monica.')
else:
print('Hello, stranger.')
if name == 'Monica':
print('Hi, Monica.')
elif age < 12:
print('You are not Monica, kiddo.')
elif age > 2000:
print('Unlike you, Monica is not an undead, immortal vampire.')
elif age > 100:
print('You are not Monica, grannie.')</code></pre>
<ul>
<li>Remember the order of <code>elif</code> statements matter.</li>
</ul>
<hr />
<h2 id="while-statements"><strong>While Statements</strong></h2>
<pre><code>spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1</code></pre>
<ul>
<li>
<p><code>Break</code> statement also exists in Python.</p>
<p>
spam = 0 while True: print(‘Hello, world.’) spam = spam + 1 if spam
>= 5: break
</p>
</li>
<li>
<p>As are <code>continue</code> statements</p>
<p>
spam = 0 while True: print(‘Hello, world.’) spam = spam + 1 if spam
< 5: continue break
</p>
</li>
</ul>
<hr />
<h2 id="tryexcept-statements"><strong>Try/Except Statements</strong></h2>
<ul>
<li>
<p>Python equivalent to <code>try/catch</code></p>
<p>
a = 321 try: print(len(a)) except: print(‘Silently handle error here’)
</p>
<pre><code># Optionally include a correction to the issue
a = str(a)
print(len(a)</code></pre>
<p>
a = ‘321’ try: print(len(a)) except: print(‘Silently handle error
here’)
</p>
<pre><code># Optionally include a correction to the issue
a = str(a)
print(len(a))</code></pre>
</li>
<li>
<p>You can name an error to give the output more specificity.</p>
<p>
a = 100 b = 0 try: c = a / b except ZeroDivisionError: c = None
print(c)
</p>
</li>
<li>
<p>
You can also use the <code>pass</code> commmand to by pass a certain
error.
</p>
<p>a = 100 b = 0 try: print(a / b) except ZeroDivisionError: pass</p>
</li>
<li>
<p>
The <code>pass</code> method won’t allow you to bypass every single
error so you can chain an exception series like so:
</p>
<p>a = 100</p>
<h1 id="b-5">b = “5”</h1>
<p>
try: print(a / b) except ZeroDivisionError: pass except (TypeError,
NameError): print(“ERROR!”)
</p>
</li>
<li>
<p>
You can use an <code>else</code> statement to end a chain of
<code>except</code> statements.
</p>
<h1 id="tuple-of-file-names">tuple of file names</h1>
<p>files = (‘one.txt’, ‘two.txt’, ‘three.txt’)</p>
<h1 id="simple-loop">simple loop</h1>
<p>
for filename in files: try: # open the file in read mode f =
open(filename, ‘r’) except OSError: # handle the case where file does
not exist or permission is denied print(‘cannot open file’, filename)
else: # do stuff with the file object (f) print(filename, ‘opened
successfully’) print(‘found’, len(f.readlines()), ‘lines’) f.close()
</p>
</li>
<li>
<p>
<code>finally</code> is used at the end to clean up all actions under
any circumstance.
</p>
<p>
def divide(x, y): try: result = x / y except ZeroDivisionError:
print(“Cannot divide by zero”) else: print(“Result is”, result)
finally: print(“Finally…”)
</p>
</li>
<li>
<p>
Using duck typing to check to see if some value is able to use a
certain method.
</p>
<h1 id="try-a-number---nothing-will-print-out">
Try a number - nothing will print out
</h1>
<p>a = 321 if hasattr(a, ‘<strong>len</strong>’): print(len(a))</p>
<h1 id="try-a-string---the-length-will-print-out-4-in-this-case">
Try a string - the length will print out (4 in this case)
</h1>
<p>b = “5555” if hasattr(b, ‘<strong>len</strong>’): print(len(b))</p>
</li>
</ul>
<hr />
<h2 id="pass"><strong>Pass</strong></h2>
<ul>
<li>
<p>Pass Keyword is required to write the JS equivalent of :</p>
<p>if (true) { }</p>
<p>while (true) {}</p>
<p>if True: pass</p>
<p>while True: pass</p>
</li>
</ul>
<hr />
<h2 id="functions"><strong>Functions</strong></h2>
<ul>
<li>
<p><strong>Function</strong> definition includes:</p>
<ul>
<li>The <code>def</code> keyword</li>
<li>The name of the function</li>
<li>A list of parameters enclosed in parentheses.</li>
<li>A colon at the end of the line.</li>
<li>One tab indentation for the code to run.</li>
</ul>
</li>
<li>
<p>You can use default parameters just like in JS</p>
<p>def greeting(name, saying=“Hello”): print(saying, name)</p>
<p>greeting(“Monica”)</p>
<h1 id="hello-monica">Hello Monica</h1>
<p>greeting(“Barry”, “Hey”)</p>
<h1 id="hey-barry">Hey Barry</h1>
</li>
<li>
<p>
Keep in mind, default parameters must always come after regular
parameters.
</p>
<h1 id="this-is-bad-code-and-will-not-run">
THIS IS BAD CODE AND WILL NOT RUN
</h1>
<p>def increment(delta=1, value): return delta + value</p>
</li>
<li>
<p>
You can specify arguments by name without destructuring in Python.
</p>
<p>def greeting(name, saying=“Hello”): print(saying, name)</p>
<h1 id="name-has-no-default-value-so-just-provide-the-value">
name has no default value, so just provide the value
</h1>
<h1 id="saying-has-a-default-value-so-use-a-keyword-argument">
saying has a default value, so use a keyword argument
</h1>
<p>greeting(“Monica”, saying=“Hi”)</p>
</li>
<li>
<p>
The <code>lambda</code> keyword is used to create anonymous functions
and are supposed to be <code>one-liners</code>.
</p>
</li>
</ul>
<p><code>toUpper = lambda s: s.upper()</code></p>
<hr />
<p>
Notes Formatted Strings Remember that in Python join() is called on a
string with an array/list passed in as the argument. shopping_list =
[‘bread’,‘milk’,‘eggs’] print(‘,’.join(shopping_list)) Python has a very
powerful formatting engine. format() is also applied directly to strings.
</p>
<h1 id="comma-thousands-separator">Comma Thousands Separator</h1>
<p>print(‘{:,}’.format(1234567890)) ‘1,234,567,890’</p>
<h1 id="date-and-time">Date and Time</h1>
<p>
d = datetime.datetime(2020, 7, 4, 12, 15, 58) print(‘{:%Y-%m-%d
%H:%M:%S}’.format(d)) ‘2020-07-04 12:15:58’
</p>
<h1 id="percentage">Percentage</h1>
<p>
points = 190 total = 220 print(‘Correct answers:
{:.2%}’.format(points/total)) Correct answers: 86.36%
</p>
<h1 id="data-tables">Data Tables</h1>
<p>
width=8 print(’ decimal hex binary’) print(‘-’*27) for num in range(1,16):
for base in ‘dXb’: print(‘{0:{width}{base}}’.format(num, base=base,
width=width), end=’ ‘) print() Getting Input from the Command Line Python
runs synchronously, all programs and processes will stop when listening
for a user input. The input function shows a prompt to a user and waits
for them to type ’ENTER’. Scripts vs Programs Programming Script : A set
of code that runs in a linear fashion. The largest difference between
scripts and programs is the level of complexity and purpose. Programs
typically have many UI’s.
</p>
<p>
Python can be used to display html, css, and JS. We will be using Python
as an API (Application Programming Interface)
</p>
<p>
Structured Data Sequence : The most basic data structure in Python where
the index determines the order.
</p>
<p>
List Tuple Range Collections : Unordered data structures, hashable values.
</p>
<p>
Dictionaries Sets Iterable : Generic name for a sequence or collection;
any object that can be iterated through. Can be mutable or immutable.
Built In Data Types Lists are the python equivalent of arrays. empty_list
= [] departments = [‘HR’,‘Development’,‘Sales’,‘Finance’,‘IT’,‘Customer
Support’]
</p>
<h1 id="you-can-instantiate">You can instantiate</h1>
<p>specials = list()</p>
<h1 id="test-if-a-value-is-in-a-list.">Test if a value is in a list.</h1>
<p>
print(1 in [1, 2, 3]) #> True print(4 in [1, 2, 3]) #> False Tuples
: Very similar to lists, but they are immutable
</p>
<h1 id="instantiated-with-parentheses">Instantiated with parentheses</h1>
<p>time_blocks = (‘AM’,‘PM’)</p>
<h1 id="sometimes-instantiated-without">Sometimes instantiated without</h1>
<p>colors = ‘red’,‘blue’,‘green’ numbers = 1, 2, 3</p>
<h1 id="tuple-built-in-can-be-used-to-convert-other-data-into-a-tuple">
Tuple() built in can be used to convert other data into a tuple
</h1>
<p>
tuple(‘abc’) # returns (‘a’, ‘b’, ‘c’) tuple([1,2,3]) # returns (1, 2, 3)
Think of tuples as constant variables.
</p>
<p>
Ranges : A list of numbers which can’t be changed; often used with for
loops. Declared using one to three parameters. Start : opt. default 0,
first # in sequence. Stop : required next number past the last number in
the sequence. Step : opt. default 1, difference between each number in the
sequence. range(5) # [0, 1, 2, 3, 4] range(1,5) # [1, 2, 3, 4] range(0,
25, 5) # [0, 5, 10, 15, 20] range(0) # [ ] for let (i = 0; i < 5; i++)
for let (i = 1; i < 5; i++) for let (i = 0; i < 25; i+=5) for let(i
= 0; i = 0; i++) Keep in mind that stop is not included in the range.
</p>
<p>
Dictionaries : Mappable collection where a hashable value is used as a key
to ref. an object stored in the dictionary. Mutable. a = {‘one’:1,
‘two’:2, ‘three’:3} b = dict(one=1, two=2, three=3) c = dict([(‘two’, 2),
(‘one’, 1), (‘three’, 3)]) a, b, and c are all equal
</p>
<p>Declared with curly braces of the built in dict()</p>
<p>
Benefit of dictionaries in Python is that it doesn’t matter how it is
defined, if the keys and values are the same the dictionaries are
considered equal.
</p>
<p>Use the in operator to see if a key exists in a dictionary.</p>
<p>
Sets : Unordered collection of distinct objects; objects that need to be
hashable.
</p>
<p>
Always be unique, duplicate items are auto dropped from the set. Common
Uses: Removing Duplicates Membership Testing Mathematical Operators:
Intersection, Union, Difference, Symmetric Difference. Standard Set is
mutable, Python has a immutable version called frozenset. Sets created by
putting comma seperated values inside braces:
</p>
<p>
school_bag =
{‘book’,‘paper’,‘pencil’,‘pencil’,‘book’,‘book’,‘book’,‘eraser’}
print(school_bag)
</p>
<h1 id="also-can-use-set-constructor-to-automatically-put-it-into-a-set.">
Also can use set constructor to automatically put it into a set.
</h1>
<p>
letters = set(‘abracadabra’) print(letters) Built-In Functions Functions
using iterables
</p>
<p>
filter(function, iterable) : creates new iterable of the same type which
includes each item for which the function returns true.
</p>
<p>
map(function, iterable) : creates new iterable of the same type which
includes the result of calling the function on every item of the iterable.
</p>
<p>
sorted(iterable, key=None, reverse=False) : creates a new sorted list from
the items in the iterable.
</p>
<p>
Output is always a list key: opt function which coverts and item to a
value to be compared. reverse: optional boolean. enumerate(iterable,
start=0) : starts with a sequence and converts it to a series of tuples
</p>
<p>
quarters = [‘First’, ‘Second’, ‘Third’, ‘Fourth’]
print(enumerate(quarters)) print(enumerate(quarters, start=1))
</p>
<h1 id="first-1-second-2-third-3-fourth">
(0, ‘First’), (1, ‘Second’), (2, ‘Third’), (3, ‘Fourth’)
</h1>
<h1 id="first-2-second-3-third-4-fourth">
(1, ‘First’), (2, ‘Second’), (3, ‘Third’), (4, ‘Fourth’)
</h1>
<p>
zip(*iterables) : creates a zip object filled with tuples that combine 1
to 1 the items in each provided iterable. Functions that analyze iterables
</p>
<p>len(iterable) : returns the count of the number of items.</p>
<p>max(*args, key=None) : returns the largest of two or more arguments.</p>
<p>max(iterable, key=None) : returns the largest item in the iterable.</p>
<p>
key optional function which converts an item to a value to be compared.
min works the same way as max
</p>
<p>sum(iterable) : used with a list of numbers to generate the total.</p>
<p>
There is a faster way to concatenate an array of strings into one string,
so do not use sum for that. any(iterable) : returns True if any items in
the iterable are true.
</p>
<p>all(iterable) : returns True is all items in the iterable are true.</p>
<p>Working with dictionaries</p>
<p>
dir(dictionary) : returns the list of keys in the dictionary. Working with
sets
</p>
<p>
Union : The pipe | operator or union(*sets) function can be used to
produce a new set which is a combination of all elements in the provided
set. a = {1, 2, 3} b = {2, 4, 6} print(a | b) # => {1, 2, 3, 4, 6}
Intersection : The & operator ca be used to produce a new set of only
the elements that appear in all sets. a = {1, 2, 3} b = {2, 4, 6} print(a
& b) # => {2} Difference : The - operator can be used to produce a
new set of only the elements that appear in the first set and NOT the
others.
</p>
<p>
Symmetric Difference : The ^ operator can be used to produce a new set of
only the elements that appear in exactly one set and not in both.
</p>
<p>
a = {1, 2, 3} b = {2, 4, 6} print(a - b) # => {1, 3} print(b - a) #
=> {4, 6} print(a ^ b) # => {1, 3, 4, 6} For Statements In python,
there is only one for loop.
</p>
<p>
Always Includes: The for keyword A variable name The in keyword An
iterable of some kid A colon On the next line, an indented block of code
called the for clause. You can use break and continue statements inside
for loops as well.
</p>
<p>You can use the range function as the iterable for the for loop.</p>
<p>
print(‘My name is’) for i in range(5): print(‘Carlita Cinco (’ + str(i) +
‘)’)
</p>
<p>
total = 0 for num in range(101): total += num print(total) Looping over a
list in Python for c in [‘a’, ‘b’, ‘c’]: print(c)
</p>
<p>
lst = [0, 1, 2, 3] for i in lst: print(i) Common technique is to use the
len() on a pre-defined list with a for loop to iterate over the indices of
the list. supplies = [‘pens’, ‘staplers’, ‘flame-throwers’, ‘binders’] for
i in range(len(supplies)): print(‘Index’ + str(i) + ’ in supplies is: ’ +
supplies[i]) You can loop and destructure at the same time. l = [[1, 2],
[3, 4], [5, 6]] for a, b in l: print(a, ‘,’, b)
</p>
<h1 id="prints-1-2">Prints 1, 2</h1>
<h1 id="prints-3-4">Prints 3, 4</h1>
<h1 id="prints-5-6">Prints 5, 6</h1>
<p>
You can use values() and keys() to loop over dictionaries. spam =
{‘color’: ‘red’, ‘age’: 42} for v in spam.values(): print(v)
</p>
<h1 id="prints-red">Prints red</h1>
<h1 id="prints-42">Prints 42</h1>
<p>for k in spam.keys(): print(k)</p>
<h1 id="prints-color">Prints color</h1>
<h1 id="prints-age">Prints age</h1>
<p>For loops can also iterate over both keys and values.</p>
<h1 id="getting-tuples">Getting tuples</h1>
<p>for i in spam.items(): print(i)</p>
<h1 id="prints-color-red">Prints (‘color’, ‘red’)</h1>
<h1 id="prints-age-42">Prints (‘age’, 42)</h1>
<h1 id="destructuring-to-values">Destructuring to values</h1>
<p>for k, v in spam.items(): print(‘Key:’ + k + ’ Value: ’ + str(v))</p>
<h1 id="prints-key-age-value-42">Prints Key: age Value: 42</h1>
<h1 id="prints-key-color-value-red">Prints Key: color Value: red</h1>
<p>
Looping over string for c in “abcdefg”: print(c) More On Functions
Variable-length positional arguments : (<em>args) def add(a, b,</em>
args): total = a + b; for n in args: total += n return total
</p>
<p>add(1, 2) # Returns 3</p>
<p>
add(2, 3, 4, 5) # Returns 14 keyword arguments : (*kwargs) def
print_names_and_countries(greeting, **kwargs): for k, v in kwargs.items():
print(greeting, k, “from”, v)
</p>
<p>
print_names_and_countries(“Hi”, Monica=“Sweden”, Charles=“British Virgin
Islands”, Carlo=“Portugal”)
</p>
<h1 id="prints">Prints</h1>
<h1 id="hi-monica-from-sweden">Hi Monica from Sweden</h1>
<h1 id="hi-charles-from-british-virgin-islands">
Hi Charles from British Virgin Islands
</h1>
<h1 id="hi-carlo-from-portugal">Hi Carlo from Portugal</h1>
<p>
When you order arguments within a function or function call, the args need
to occur in a particular order: formal positional args.
<em
>args keyword args with default values **kwargs def example(arg_1,
arg_2,</em
>
args, **kwargs): pass
</p>
<p>
def example2(arg_1, arg_2, *args, kw_1=“shark”, kw_2=“blowfish”,
**kwargs): pass Importing in Python Modules are similar to packages in
Node.js Come in different types: Built-In, Third-Party, Custom. All loaded
using import statements. Terms
</p>
<p>
module : Python code in a separate file. package : Path to a directory
that contains modules. <strong>init.py</strong> : Default file for a
package. submodule : Another file in a module’s folder. function :
Function in a module.
</p>
<p>
A module can be any file but it is usually created by placing a special
file <strong>init</strong>.py into a folder. pic
</p>
<p>Try to avoid importing with wildcards in Python.</p>
<p>Use multiple lines for clarity when importing.</p>
<p>
from urllib.request import ( HTTPDefaultErrorHandler as ErrorHandler,
HTTPRedirectHandler as RedirectHandler, Request, pathname2url,
url2pathname, urlopen, ) Watching Out for Python 2 Python 3 removed
<> and only uses !=
</p>
<p>
format() was introduced with P3 All strings in P3 are unicode and encoded.
md5 was removed. ConfigParser was renamed to configparser sets were killed
in favor of set() class.
</p>
<p>print was a statement in P2, but is a function in P3.</p>
<h1 id="topics-revisited-in-python-syntax">
Topics revisited (in python syntax)
</h1>
<pre><code>def say_hi(name):
"""<---- Multi-Line Comments and Docstrings
This is where you put your content for help() to inform the user
about what your function does and how to use it
"""
print(f"Hello {name}!")
print(say_hi("Michael")) # Should get the print inside the function, then None
# Boolean Values
# Work the same as in JS, except they are title case: True and False
a = True
b = False
# Logical Operators
# ! = not, || = or, && = and
print(True and True)
print(True and not True)
print(True or True)
# Truthiness - Everything is True except...
# False - None, False, '', [], (), set(), range(0)
# Number Values
# Integers are numbers without a floating decimal point
print(type(3)) # type returns the type of whatever argument you pass in
# Floating Point values are numbers with a floating decimal point
print(type(3.5))
# Type Casting
# You can convert between ints and floats (along with other types...)
print(float(3)) # If you convert a float to an int, it will truncate the decimal
print(int(4.5))
print(type(str(3)))
# Python does not automatically convert types like JS
# print(17.0 + ' heyooo ' + 17) # TypeError
# Arithmetic Operators
# ** - exponent (comparable to Math.pow(num, pow))
# // - integer division
# There is no ++ or -- in Python
# String Values
# We can use single quotes, double quotes, or f'' for string formats
# We can use triple single quotes for multiline strings
print(
"""This here's a story
All about how
My life got twist
Turned upside down
"""
)
# Three double quotes can also be used, but we typically reserve these for
# multi-line comments and function docstrings (refer to lines 6-9)(Nice :D)
# We use len() to get the length of something
print(len("Michael")) # 7 characters
print(len(["hey", "ho", "hey", "hey", "ho"])) # 5 list items
print(len({1, 2, 3, 4, 5, 6, 7, 9})) # 8 set items
# We can index into strings, list, etc..self.
name = "Michael"
for i in range(len(name)):
print(name[i]) # M, i, c, h, a, e, l
# We can index starting from the end as well, with negatives
occupation = "Full Stack Software Engineer"
print(occupation[-3]) # e
# We can also get ranges in the index with the [start:stop:step] syntax
print(occupation[0:4:1]) # step and stop are optional, stop is exclusive
print(occupation[::4]) # beginning to end, every 4th letter
print(occupation[4:14:2]) # Let's get weird with it!
# NOTE: Indexing out of range will give you an IndexError
# We can also get the index og things with the .index() method, similar to indexOf()
print(occupation.index("Stack"))
print(["Mike", "Barry", "Cole", "James", "Mark"].index("Cole"))
# We can count how many times a substring/item appears in something as well
print(occupation.count("S"))