-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheatsheet.html
More file actions
854 lines (759 loc) · 37.1 KB
/
cheatsheet.html
File metadata and controls
854 lines (759 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cheatsheet — python-mania</title>
<link rel="stylesheet" href="assets/index.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js" integrity="sha384-XjKyOOlGwcjNTAIQHIpgOno0Hl1YQqzUOEleOLALmuqehneUG+vnGctmUb0ZY0l8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/a11y-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
</head>
<body>
<header class="site-header">
<div class="container header-inner">
<a class="brand" href="index.html">python-mania</a>
<button id="nav-toggle" class="nav-toggle" aria-label="Toggle navigation">☰</button>
<nav id="site-nav" class="nav" aria-label="Main navigation">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="slides.html">Slides</a></li>
<li><a href="cheatsheet.html">Cheatsheet</a></li>
<li><a href="recordings.html">Recordings</a></li>
</ul>
</nav>
</div>
</header>
<main class="container main-content">
<section class="content">
<h1 class="section-title">Python Cheatsheet for Quick Reference</h1>
<p class="muted">A comprehensive overview of core Python concepts.</p>
<div class="table-of-contents">
<h2>Table of Contents</h2>
<nav class="toc-nav">
<ul>
<li><a href="#help">Using Help Function (For OPPE)</a></li>
<li><a href="#basics">Basics & Variables</a></li>
<li><a href="#datatypes">Data Types & Typecasting</a></li>
<li><a href="#operators">Operators</a>
<ul>
<li><a href="#arithmetic">Arithmetic Operators</a></li>
<li><a href="#relational">Relational Operators</a></li>
<li><a href="#logical">Logical Operators</a></li>
<li><a href="#shorthand">Shorthand Operators</a></li>
</ul>
</li>
<li><a href="#strings">Strings</a></li>
<li><a href="#printing">Formatted Printing</a></li>
<li><a href="#control-flow">Control Flow</a></li>
<li><a href="#loops">Loops</a></li>
<li><a href="#collections">Collections</a></li>
<li><a href="#comprehensions">Comprehensions</a></li>
<li><a href="#functions">Functions & Best Practices</a></li>
<li><a href="#recursion">Recursion</a></li>
<li><a href="#modules">Modules & Libraries</a></li>
<li><a href="#files">File Handling</a></li>
<li><a href="#exceptions">Exception Handling</a></li>
</ul>
</nav>
</div>
<hr/>
<h2 id="basics">Basics & Variables</h2>
<ul>
<li><strong>Print Output</strong>: <code>print("Hello World")</code></li>
<li><strong>Input</strong>: <code>input()</code> takes user input as a string.</li>
<li><strong>Variables</strong>: Used to store values like numbers or text.</li>
<li><strong>Dynamic Typing</strong>: A variable's type is determined by the value it holds and can change.</li>
<li><strong>Multiple Assignment</strong>: <code>x, y, z = 1, "Hi", False</code></li>
<li><strong>Delete Variable</strong>: <code>del x</code> removes the variable from memory.</li>
</ul>
<hr/>
<h2 id="datatypes">Data Types & Typecasting</h2>
<table>
<thead>
<tr>
<th>Data Type</th>
<th>Example</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>int</code></td>
<td><code>a = 10</code></td>
<td>Integer (Whole Number)</td>
</tr>
<tr>
<td><code>float</code></td>
<td><code>n = 10.3</code></td>
<td>Floating Point (Decimal)</td>
</tr>
<tr>
<td><code>str</code></td>
<td><code>s = "Student"</code></td>
<td>String (Text)</td>
</tr>
<tr>
<td><code>bool</code></td>
<td><code>t = True</code></td>
<td>Boolean (True or False)</td>
</tr>
</tbody>
</table>
<h3>Type Conversion (<code>Typecasting</code>)</h3>
<ul>
<li>Convert to <strong>Integer</strong>: <code>a = int(10.1)</code> (converts <code>10.1</code> to <code>10</code>)</li>
<li>Convert to <strong>String</strong>: <code>c = str(10.3)</code> (converts <code>10.3</code> to <code>"10.3"</code>)</li>
<li><strong>Boolean Conversion</strong>: <code>bool(0)</code> is <code>False</code>. Any non-zero number or non-empty string is <code>True</code>.</li>
<li><strong>Get Type</strong>: <code>type(value)</code> returns the datatype of a variable or value.</li>
</ul>
<hr/>
<h2 id="operators">Operators</h2>
<h3 id="arithmetic">Arithmetic Operators</h3>
<table>
<thead>
<tr>
<th>Operator</th>
<th>Name</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td>
<td>Addition / Concatenation</td>
<td>Addition for <code>int</code>/<code>float</code>, Concatenation for <code>str</code>.</td>
</tr>
<tr>
<td><code>-</code></td>
<td>Subtraction</td>
<td>Subtraction.</td>
</tr>
<tr>
<td><code>*</code></td>
<td>Multiplication / Repetition</td>
<td>Multiplication for <code>int</code>/<code>float</code>, Repetition for <code>str</code>.</td>
</tr>
<tr>
<td><code>/</code></td>
<td>Division</td>
<td>Returns a <code>float</code> result.</td>
</tr>
<tr>
<td><code>//</code></td>
<td>Floor Division</td>
<td>Returns the integer quotient (integer division).</td>
</tr>
<tr>
<td><code>%</code></td>
<td>Modulus</td>
<td>Returns the remainder after division.</td>
</tr>
<tr>
<td><code>**</code></td>
<td>Exponentiation</td>
<td>Power calculation.</td>
</tr>
</tbody>
</table>
<h3 id="relational">Relational (Comparison) Operators</h3>
<p>Compare two values and return <code>True</code> or <code>False</code>.</p>
<ul>
<li><code>></code>: Greater than</li>
<li><code><</code>: Less than</li>
<li><code>>=</code>: Greater than or equal</li>
<li><code><=</code>: Less than or equal</li>
<li><code>==</code>: Equal</li>
<li><code>!=</code>: Not equal</li>
<li><strong>Chaining</strong>: Use multiple relational operators together, e.g., <code>print(1 < x < 6)</code>.</li>
</ul>
<h3 id="logical">Logical Operators</h3>
<table>
<thead>
<tr>
<th>Operator</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>and</code></td>
<td>Returns <code>True</code> if both left and right sides are true.</td>
</tr>
<tr>
<td><code>or</code></td>
<td>Returns <code>False</code> only if both left and right sides are false.</td>
</tr>
<tr>
<td><code>not</code></td>
<td>Returns the negation of the given operand.</td>
</tr>
</tbody>
</table>
<h3 id="shorthand">Shorthand (Assignment) Operators</h3>
<p>Any operator with the <code>=</code> sign, e.g., <code>+=</code>, <code>-=</code>, <code>*=</code>, etc..</p>
<pre><code>num = num + 7 # Same as...
num += 7
num = num * 2 # Same as...
num *= 2
</code></pre>
<h3>Membership Operator</h3>
<ul>
<li><code>in</code>: Checks if an item is inside or a part of another thing.
<pre><code>print("IT" in " IIT Madras ") # Output: True</code></pre>
</li>
</ul>
<hr/>
<h2 id="strings">Strings</h2>
<ul>
<li>Can be defined with single (<code>'Hello'</code>) or double quotes (<code>"World"</code>).</li>
<li><strong>Indexing</strong>: Starts from 0. <code>s1[0]</code> is the first character. Negative index <code>-1</code> is the last character.</li>
<li><strong>Slicing</strong>: <code>s1[start:stop:step]</code>. <code>s1[0:3]</code> gives characters at indices 0, 1, 2.</li>
<li><strong>Length</strong>: <code>len(s1)</code> returns the number of characters.</li>
<li><strong>Comparison</strong>: Based on alphabetical/dictionary order.</li>
<li><strong>Multiline Strings</strong>: Defined using triple quotes (<code>"""..."""</code>) (similar to multiline comments).</li>
<li><strong>Immutability</strong>: Strings cannot be changed in place.</li>
</ul>
<h3>Escape Characters</h3>
<p>Use a backslash (<code>\</code>) to insert illegal characters or special formatting.</p>
<ul>
<li><code>\'</code>: Single quote (e.g., <code>print('It\'s Raining')</code>)</li>
<li><code>\n</code>: Newline (cursor moves to the next line)</li>
<li><code>\t</code>: Tab (shifts cursor by 5 spaces)</li>
</ul>
<h3>String Methods</h3>
<table>
<thead>
<tr>
<th>Method</th>
<th>Description</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>lower()</code></td>
<td>Converts a string into lower case.</td>
<td><code>"Python".lower()</code> → <code>"python"</code></td>
</tr>
<tr>
<td><code>upper()</code></td>
<td>Converts a string into upper case.</td>
<td><code>"Python".upper()</code> → <code>"PYTHON"</code></td>
</tr>
<tr>
<td><code>capitalize()</code></td>
<td>Converts the first character to upper case.</td>
<td><code>"python".capitalize()</code> → <code>"Python"</code></td>
</tr>
<tr>
<td><code>title()</code></td>
<td>Converts the first char of each word to upper case.</td>
<td><code>"py string".title()</code> → <code>"Py String"</code></td>
</tr>
<tr>
<td><code>swapcase()</code></td>
<td>Swaps cases (lower becomes upper, vice versa).</td>
<td><code>"Py".swapcase()</code> → <code>"pY"</code></td>
</tr>
<tr>
<td><code>strip()</code></td>
<td>Returns a trimmed version of the string (removes leading/trailing whitespace or specified chars).</td>
<td><code>"-Python-".strip('-')</code> → <code>"Python"</code></td>
</tr>
<tr>
<td><code>replace(old, new)</code></td>
<td>Returns a string where a specified value is replaced.</td>
<td><code>"A B".replace('A', 'C')</code> → <code>"C B"</code></td>
</tr>
<tr>
<td><code>index(x)</code></td>
<td>Returns the index of the first occurrence of <code>x</code>.</td>
<td><code>"python".index('t')</code> → <code>2</code></td>
</tr>
<tr>
<td><code>count(x)</code></td>
<td>Returns the number of times <code>x</code> occurs in the string.</td>
<td><code>"Hello".count('l')</code> → <code>2</code></td>
</tr>
</tbody>
</table>
<h3>String Test Methods (Boolean Return)</h3>
<ul>
<li><code>islower()</code>: <code>True</code> if all cased characters are lowercase.</li>
<li><code>isupper()</code>: <code>True</code> if all cased characters are uppercase.</li>
<li><code>istitle()</code>: <code>True</code> if the string follows title rules.</li>
<li><code>isdigit()</code>: <code>True</code> if all characters are digits.</li>
<li><code>isalpha()</code>: <code>True</code> if all characters are in the alphabet.</li>
<li><code>isalnum()</code>: <code>True</code> if all characters are alphanumeric (a-z, A-Z, 0-9).</li>
<li><code>startswith(x)</code>: <code>True</code> if the string starts with <code>x</code>.</li>
<li><code>endswith(x)</code>: <code>True</code> if the string ends with <code>x</code>.</li>
</ul>
<hr/>
<h2 id="printing">Formatted Printing</h2>
<h3>1. f-Strings (Recommended)</h3>
<p>Prefix the string with <code>f</code> and embed expressions in curly braces <code>{}</code>.</p>
<pre><code>x = 5; pi = 22/7
print(f"value of x is {x}") # Output: value of x is 5
print(f"value of pi is {pi:.3f}") # Output: value of pi is 3.143 (3 decimal places)
print(f"value of x is {x:5d}") # Output: value of x is 5 (width of 5 chars, right-aligned)
</code></pre>
<h3>2. Modulo Operator (%) - (C-Style)</h3>
<p>Use <code>%</code> followed by a format specifier (<code>%d</code> for int, <code>%f</code> for float).</p>
<pre><code>x = 5; pi = 22/7
print("x = %d, pi = %f" % (x, pi)) # Output: x = 5, pi = 3.142857
print("x = %5d, pi = %.4f" % (x, pi)) # Output: x = 5, pi = 3.1429 (width 5 for x, 4 decimals for pi)
</code></pre>
<h3>3. <code>sep</code> and <code>end</code> parameters in <code>print()</code></h3>
<ul>
<li><code>sep</code>: Specifies the separator between arguments (default is a space).
<pre><code>print("11", "06", "24", sep="/") # Output: 11/06/24</code></pre>
</li>
<li><code>end</code>: Specifies what to print after the statement (default is a newline <code>\n</code>).
<pre><code>print("Hello", end = ", ")
print("Python") # Output: Hello, Python</code></pre>
</li>
</ul>
<hr/>
<h2 id="control-flow">Control Flow (if-elif-else)</h2>
<p>Uses <strong>indentation</strong> to define code blocks.</p>
<pre><code>if (condition):
# Statement 1 (executed if condition is True)
elif (condition):
# Statement 2 (optional, executed if previous conditions are False)
else:
# Statement 3 (optional, executed if all previous conditions are False)
</code></pre>
<h3>Single-Line Control Flow</h3>
<ul>
<li><strong>If Statement</strong>: <code>if condition: block</code>
<pre><code>if a % 2 == 0: print('even')</code></pre>
</li>
<li><strong>If-Else Statement (Ternary Operator)</strong>: <code>block1 if condition else block2</code>
<pre><code>print('even') if a % 2 == 0 else print('odd')</code></pre>
</li>
</ul>
<hr/>
<h2 id="loops">Loops</h2>
<p>A loop executes a block of statements repeatedly.</p>
<h3>1. <code>while</code> Loop</h3>
<p>Executes statements repeatedly until a given <strong>condition is satisfied</strong>. Used when the number of iterations is <strong>not known</strong>.</p>
<pre><code>while condition:
# body of while loop
# increment/decrement counter (to avoid infinite loop)
</code></pre>
<h3>2. <code>for</code> Loop</h3>
<p>Used to <strong>iterate over sequences</strong> (string, list, tuple, dict, set) or any iterable object. Used when the number of iterations is <strong>known</strong>.</p>
<pre><code># For Each Loop
for var in iterable:
# statements
# For Loop with range()
for var in range(start, stop, step):
# statements
</code></pre>
<ul>
<li><code>range(stop)</code>: Generates numbers from <code>0</code> up to <code>stop-1</code> (step is <code>1</code>).</li>
<li><code>range(start, stop)</code>: Generates numbers from <code>start</code> up to <code>stop-1</code> (step is <code>1</code>).</li>
<li><code>range(start, stop, step)</code>: Generates numbers from <code>start</code> up to <code>stop-1</code>, increasing by <code>step</code>.</li>
</ul>
<h3>Loop Control Statements</h3>
<ul>
<li><strong><code>break</code></strong>: Terminates the current loop immediately.
<pre><code>if condition:
break</code></pre>
</li>
<li><strong><code>continue</code></strong>: Skips the remaining statements in the current iteration and forces execution of the next iteration.
<pre><code>if condition:
continue</code></pre>
</li>
<li><strong><code>pass</code></strong>: Does nothing. Used when a statement is syntactically required but no code should execute (e.g., in empty loops, functions, or classes).
<pre><code>if condition:
pass</code></pre>
</li>
</ul>
<hr/>
<h2 id="collections">Collections (Data Structures)</h2>
<table>
<thead>
<tr>
<th>Collection</th>
<th>Notation</th>
<th>Mutability</th>
<th>Order</th>
<th>Duplicate Elements</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>List</strong></td>
<td><code>[ ]</code> (Square Brackets)</td>
<td><strong>Mutable</strong> (Can be updated in place)</td>
<td>Ordered</td>
<td>Allowed</td>
</tr>
<tr>
<td><strong>Tuple</strong></td>
<td><code>( )</code> (Parentheses)</td>
<td><strong>Immutable</strong> (Cannot be changed in place)</td>
<td>Ordered</td>
<td>Allowed</td>
</tr>
<tr>
<td><strong>Set</strong></td>
<td><code>{ }</code> (Curly Braces) or <code>set()</code></td>
<td><strong>Mutable</strong></td>
<td>Unordered</td>
<td>Not allowed (Unique items)</td>
</tr>
<tr>
<td><strong>Dictionary</strong></td>
<td><code>{key: value}</code></td>
<td><strong>Mutable</strong></td>
<td>Unordered (Ordered in Python 3.7+)</td>
<td>Keys: Not allowed. Values: Allowed.</td>
</tr>
</tbody>
</table>
<h3>List Methods & Functions</h3>
<ul>
<li><strong>Methods</strong>: <code>list.append(x)</code>, <code>list.insert(i, x)</code>, <code>list.extend(iterable)</code>, <code>list.remove(x)</code>, <code>list.pop(i)</code> (removes and returns), <code>list.sort()</code>, <code>list.reverse()</code>.</li>
<li><strong>Functions</strong>: <code>len(list)</code>, <code>max(list)</code>, <code>min(list)</code>, <code>sum(list)</code>.</li>
<li><code>sorted(list)</code>: Returns a <strong>new</strong> sorted list.</li>
<li><strong>Slicing</strong>: <code>list[start:end:step]</code></li>
<li><strong>Concatenation</strong>: <code>a + b</code></li>
<li><strong>Deletion</strong>: <code>del a[i]</code> or <code>del a[i:j]</code></li>
</ul>
<h3>Dictionary Operations</h3>
<ul>
<li><strong>Creation</strong>: <code>Dict = {}</code> or <code>Dict = dict()</code>.</li>
<li><strong>Access</strong>: <code>Dict[key]</code> or <code>Dict.get(key, default)</code>.</li>
<li><strong>Add/Update</strong>: <code>Dict[new_key] = new_value</code> (updates if key exists, adds otherwise).</li>
<li><strong>Methods</strong>: <code>Dict.clear()</code>, <code>Dict.copy()</code>, <code>Dict.keys()</code>, <code>Dict.values()</code>, <code>Dict.items()</code>, <code>Dict.pop(key)</code>, <code>Dict.popitem()</code>, <code>Dict.update()</code>.</li>
<li><strong>Keys must be Hashable</strong>: Immutable types like strings and tuples are valid keys.</li>
</ul>
<h3>Set Operations (with <code>set1 = {1, 2, 3, 4}</code>, <code>set2 = {1, 3, 5}</code>)</h3>
<table>
<thead>
<tr>
<th>Operation</th>
<th>Expression</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>Union</td>
<td><code>set1 | set2</code></td>
<td><code>{1, 2, 3, 4, 5}</code></td>
</tr>
<tr>
<td>Intersection</td>
<td><code>set1 & set2</code></td>
<td><code>{1, 3}</code></td>
</tr>
<tr>
<td>Difference</td>
<td><code>set1 - set2</code></td>
<td><code>{2, 4}</code></td>
</tr>
<tr>
<td>Symmetric Difference</td>
<td><code>set1 ^ set2</code></td>
<td><code>{2, 4, 5}</code></td>
</tr>
<tr>
<td>Subset Check</td>
<td><code>set1 <= set2</code></td>
<td><code>False</code></td>
</tr>
</tbody>
</table>
<ul>
<li><strong>Methods</strong>: <code>set.add(x)</code>, <code>set.remove(x)</code> (raises error), <code>set.discard(x)</code> (no error if not found), <code>set.pop()</code> (removes random element).</li>
<li><strong>Elements must be Hashable</strong>: Mutable objects (lists, dictionaries, sets) cannot be set elements.</li>
</ul>
<hr/>
<h2 id="comprehensions">Comprehensions</h2>
<h3>List Comprehension (Mapping)</h3>
<p>A concise way to create lists from existing iterables.</p>
<pre><code>L = [f(x) for x in iterable]
# Example: Square of elements in L1
L1 = [1, 2, 3, 4]
L = [x**2 for x in L1] # L -> [1, 4, 9, 16]
</code></pre>
<h3>List Comprehension (Filtering & Mapping)</h3>
<p>Includes an <code>if</code> condition for filtering.</p>
<pre><code>L = [f(x) for x in iterable if condition]
# Example: Only even elements of L1
L = [x for x in L1 if x % 2 == 0] # L -> [2, 4]
</code></pre>
<h3>List Comprehension (if-else)</h3>
<p>Includes a conditional expression using <code>if-else</code> (note its position at the start).</p>
<pre><code>L = [f(x) if condition else g(x) for x in iterable]
</code></pre>
<hr/>
<h2 id="functions">Functions & Best Practices</h2>
<h3>Defining a Function</h3>
<p>A reusable block of statements for a specific task.</p>
<pre><code>def function_name(parameters): # Keyword, name, and parameters
# Body of statements
return expression # Returns a value (optional)
</code></pre>
<h3>Arguments</h3>
<ul>
<li><strong>Positional Arguments</strong>: Values are assigned based on their position/order.</li>
<li><strong>Keyword Arguments</strong>: Caller specifies argument names with values, so order doesn't matter.
<pre><code>sub(x=30, y=10) # Keyword
sub(10, 30) # Positional (results in 10-30 = -20)</code></pre>
</li>
<li><strong>Default Arguments</strong>: A parameter assumes a default value if not provided in the call.
<pre><code>def add(x, y=100): return x + y
add(10) # Uses y=100, returns 110</code></pre>
</li>
<li><strong>Multiple Returns</strong>: Functions can return multiple values separated by commas (returned as a tuple).
<pre><code>return x_squared, y_squared, z_squared</code></pre>
</li>
</ul>
<h3>Type Hinting (Industry Practice)</h3>
<p>Though not strictly required by the Python interpreter, using <strong>type hints</strong> (<code>: type -> type</code>) is a best practice for clarity and static analysis.</p>
<pre><code># Defines a function taking a float and returning a float
def calculate_area(length: float, width: float) -> float:
return length * width
</code></pre>
<hr/>
<h2 id="recursion">Recursion</h2>
<p>The process of calling a function within itself.</p>
<ul>
<li><strong>Base Case</strong>: The condition that stops the recursion (must return a value).</li>
<li><strong>Recursive Case</strong>: The part of the function that calls itself, working towards the base case.</li>
</ul>
<pre><code>def factorial(n):
if n == 0: # Base Case
return 1
return n * factorial(n-1) # Recursive Case
</code></pre>
<hr/>
<h2 id="modules">Modules & Libraries</h2>
<p>Ways to import libraries:</p>
<pre><code># 1. Imports entire library, requires "math." prefix
import math
print(math.sqrt(2))
# 2. Imports all contents, no prefix needed, generally discouraged
from math import *
print(sqrt(2))
# 3. Imports specific function, no prefix needed
from math import sqrt
print(sqrt(2))
# 4. Imports and renames the function
from math import sqrt as s
print(s(2))
</code></pre>
<hr/>
<h2 id="files">File Handling (I/O)</h2>
<p>Syntax to open a file: <code>file = open(file_path, mode)</code></p>
<h3>Important Modes</h3>
<table>
<thead>
<tr>
<th>Mode</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>r</code></td>
<td>Read operation. Throws error if file doesn't exist.</td>
</tr>
<tr>
<td><code>w</code></td>
<td>Write operation. <strong>Overrides</strong> existing data or creates a new file.</td>
</tr>
<tr>
<td><code>a</code></td>
<td>Append operation. <strong>Won't override</strong> existing data, adds to the end.</td>
</tr>
<tr>
<td><code>r+</code></td>
<td>Read and write. Does not override existing data.</td>
</tr>
<tr>
<td><code>w+</code></td>
<td>Write and read. Overwrites the file to zero length.</td>
</tr>
<tr>
<td><code>a+</code></td>
<td>Append and read. Won't override existing data.</td>
</tr>
</tbody>
</table>
<h3>Reading Methods</h3>
<ul>
<li><code>file.read()</code>: Extracts the entire content of the file as a single string.</li>
<li><code>file.readline()</code>: Reads a single line from the file and returns it as a string.</li>
<li><code>file.readlines()</code>: Reads all lines of the file and returns them as a <strong>list of strings</strong>.</li>
</ul>
<h3>Writing Methods</h3>
<ul>
<li><code>file.write(string)</code>: Writes the given string to the file (requires <code>\n</code> for a new line).</li>
<li><code>file.writelines(iterable)</code>: Writes a sequence of strings (e.g., a list of strings) to the file.</li>
</ul>
<h3>File Pointer Control</h3>
<ul>
<li><code>file.close()</code>: Closes the file (good practice).</li>
<li><code>file.tell()</code>: Returns the <strong>current position</strong> of the File Handle (cursor).</li>
<li><code>file.seek(offset, from_what)</code>: Changes the position of the File Handle.
<ul>
<li><code>from_what=0</code>: Start of the file (default)</li>
<li><code>from_what=1</code>: Current file position</li>
<li><code>from_what=2</code>: End of the file</li>
</ul>
</li>
</ul>
<hr/>
<h2 id="exceptions">Exception Handling (try-except)</h2>
<p>Used to handle errors gracefully, allowing the program to continue execution instead of stopping abruptly.</p>
<pre><code>try:
# Code that may cause exception
except ExceptionType:
# Code to run when a specific exception occurs
except:
# Code to run for any other exception (generic)
else:
# Code that runs ONLY IF no exception occurred in the 'try' block
finally:
# Code that ALWAYS runs, regardless of whether an exception occurred or not
</code></pre>
<h3>Common Exceptions</h3>
<ul>
<li><strong><code>SyntaxError</code></strong>: Invalid code structure.</li>
<li><strong><code>TypeError</code></strong>: Operation applied to an object of the wrong type (e.g., adding string to int).</li>
<li><strong><code>NameError</code></strong>: Variable or function name not found in the current scope.</li>
<li><strong><code>IndexError</code></strong>: Index is out of range for a list/tuple.</li>
<li><strong><code>KeyError</code></strong>: Key not found in a dictionary.</li>
<li><strong><code>ZeroDivisionError</code></strong>: Attempt to divide a number by zero.</li>
<li><strong><code>FileNotFoundError</code></strong>: File not found when trying to open/access it.</li>
</ul>
<h3>Raising an Exception</h3>
<p>The <code>raise</code> statement forces a specific exception to occur.</p>
<pre><code>if x > 3:
raise Exception("Value is greater than 3")
</code></pre>
<h2 id="help">🐍 The Python Help Function: Your Built-in Guide/Help for OPPE or in general programming</h2>
<p>
The built-in <code>help()</code> function is one of Python's most powerful tools. It provides interactive access to the documentation for modules, keywords, functions, classes, and methods. It works by reading the <strong>docstrings</strong> (documentation strings, written as <code>"""..."""</code>) that are built directly into the code.
</p>
<h3>1. Getting Help on Built-in Types (Classes)</h3>
<p>
You can get a full "manual page" for any built-in data type, like strings, lists, or dictionaries. This will show you the class description and a list of all its available methods.
</p>
<pre><code>
# Get all information about the string class
help(str)
# Get all information about the list class
help(list)
# Get all information about the dictionary class
help(dict)
</code></pre>
<p>
The output will list all methods, including "dunder" (double-underscore) methods like <code>__init__</code> or <code>__add__</code>.
</p>
<h3>2. Getting Help on Specific Methods</h3>
<p>
If you don't want to read the entire manual, you can ask for help on one specific method. This is much faster and more focused.
</p>
<pre><code>
# Get help just for the string's 'lower' method
help(str.lower)
# Get help just for the list's 'append' method
help(list.append)
# Get help for the dictionary's 'get' method
help(dict.get)
</code></pre>
<p>
This will show you exactly what the method does, what arguments it takes, and what it returns.
</p>
<h3>3. Getting Help on Built-in Functions</h3>
<p>
You can get documentation for any of Python's built-in functions.
</p>
<pre><code>
# Get help for the 'len' function
help(len)
# Get help for the 'print' function
# (This is useful for learning about 'sep' and 'end' arguments)
help(print)
# Get help for the 'range' function
help(range)
</code></pre>
<h3>4. Getting Help on an Object (Instance)</h3>
<p>
This is a key concept for Object-Oriented Programming (OOP). You don't need to know the <em>class</em> of an object; you can just pass the <em>object itself</em> (the instance) to <code>help()</code>.
</p>
<pre><code>
# Create an instance of a list
my_list = [1, 2, 3]
# This will automatically detect it's a list and give you help(list)
help(my_list)
# Create an instance of a string
my_name = "Alice"
# This will give you help(str)
help(my_name)
</code></pre>
<h3>5. Getting Help on Your Own Custom Classes (OOP)</h3>
<p>
The <code>help()</code> function will also work on your own classes and methods, <em>if</em> you write docstrings for them.
</p>
<pre><code>
class Car:
"""
A simple class to represent a Car.
"""
def __init__(self, make, model):
"""Initializes a new Car instance."""
self.make = make
self.model = model
def start_engine(self):
"""Prints a message to start the engine."""
print(f"{self.make} {self.model}'s engine is running.")
# --- Now, let's use help() on our class ---
# 1. Get help on the CLASS itself
help(Car)
# 2. Get help on a METHOD of the class
help(Car.start_engine)
# 3. Get help on an INSTANCE of the class
my_car = Car("Tesla", "Model 3")
help(my_car)
</code></pre>
<p>
Running <code>help(Car)</code> will neatly display all your custom docstrings, showing the class description and its methods. This is essential for writing code that others (and your future self) can understand.
</p>
<h3>Running <code>help()</code> in a Terminal</h3>
<p>
When you use <code>help()</code> in a command prompt or terminal (not in a notebook like Google Colab), it often opens a special viewer.
</p>
<blockquote>
<strong>Tip:</strong> To exit this help viewer, simply press the <code>q</code> key on your keyboard.
</blockquote>
</section>
</main>
<footer class="site-footer">
<div class="container">
<ul>
<li>Contact:</li>
<ul>
<li>SAANJHI VARSHNEY (24f2003813 DS) (Operational)</li>
<li>DIVY PRAKASH (24f3004288 DS) (Operational)</li>
<li>KARTIK CHILLKOTI (24f2004962 DS) (Mentor)</li>
<li>DEVAM SHAH (24f2000828 DS) (Mentor)</li>
</ul>
<li><a href="https://github.com/Devamm007/python-mania" target="_blank" rel="noopener">GitHub - Devamm007<i class="fab fa-github"></i></a></li>
</ul>
<small class="muted">Cheatsheet • python-mania • © 2025</small>
</div>
</footer>
<script src="assets/index.js"></script>
</body>
</html>