forked from labex-labs/python-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREADME.md.backup
More file actions
4137 lines (3047 loc) · 95.4 KB
/
README.md.backup
File metadata and controls
4137 lines (3047 loc) · 95.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# About [](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master)
Basic cheatsheet for Python mostly based on the book written by Al Sweigart, [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) under the [Creative Commons license](https://creativecommons.org/licenses/by-nc-sa/3.0/) and many other sources.
## Contribute
All contributions are welcome:
- Read the issues, Fork the project and do a Pull Request.
- Request a new topic creating a `New issue` with the `enhancement` tag.
- Find any kind of errors in the cheat sheet and create a `New issue` with the details or fork the project and do a Pull Request.
- Suggest a better or more pythonic way for existing examples.
## Read It
- [Online](https://wilfredinni.github.io/python-cheatsheet/)
- [Github](https://github.com/wilfredinni/python-cheatsheet)
- [PDF](https://github.com/wilfredinni/Python-cheatsheet/raw/master/python_cheat_sheet.pdf)
- [Jupyter Notebook](https://mybinder.org/v2/gh/wilfredinni/python-cheatsheet/master?filepath=python_cheat_sheet.ipynb)
## Python Cheatsheet
- [Python Basics](#python-basics)
- [Math Operators](#math-operators)
- [Data Types](#data-types)
- [String Concatenation and Replication](#string-concatenation-and-replication)
- [Variables](#variables)
- [Comments](#comments)
- [The print() Function](#the-print-function)
- [The input() Function](#the-input-function)
- [The len() Function](#the-len-function)
- [The str(), int(), and float() Functions](#the-str-int-and-float-functions)
- [Flow Control](#flow-control)
- [Comparison Operators](#comparison-operators)
- [Boolean evaluation](#boolean-evaluation)
- [Boolean Operators](#boolean-operators)
- [Mixing Boolean and Comparison Operators](#mixing-boolean-and-comparison-operators)
- [if Statements](#if-statements)
- [else Statements](#else-statements)
- [elif Statements](#elif-statements)
- [while Loop Statements](#while-loop-statements)
- [break Statements](#break-statements)
- [continue Statements](#continue-statements)
- [for Loops and the range() Function](#for-loops-and-the-range-function)
- [For else statement](#for-else-statement)
- [Importing Modules](#importing-modules)
- [Ending a Program Early with sys.exit()](#ending-a-program-early-with-sysexit)
- [Functions](#functions)
- [Return Values and return Statements](#return-values-and-return-statements)
- [The None Value](#the-none-value)
- [Keyword Arguments and print()](#keyword-arguments-and-print)
- [Local and Global Scope](#local-and-global-scope)
- [The global Statement](#the-global-statement)
- [Exception Handling](#exception-handling)
- [Basic exception handling](#basic-exception-handling)
- [Final code in exception handling](#final-code-in-exception-handling)
- [Lists](#lists)
- [Getting Individual Values in a List with Indexes](#getting-individual-values-in-a-list-with-indexes)
- [Negative Indexes](#negative-indexes)
- [Getting Sublists with Slices](#getting-sublists-with-slices)
- [Getting a List’s Length with len()](#getting-a-list%E2%80%99s-length-with-len)
- [Changing Values in a List with Indexes](#changing-values-in-a-list-with-indexes)
- [List Concatenation and List Replication](#list-concatenation-and-list-replication)
- [Removing Values from Lists with del Statements](#removing-values-from-lists-with-del-statements)
- [Using for Loops with Lists](#using-for-loops-with-lists)
- [Looping Through Multiple Lists with zip()](#looping-through-multiple-lists-with-zip)
- [The in and not in Operators](#the-in-and-not-in-operators)
- [The Multiple Assignment Trick](#the-multiple-assignment-trick)
- [Augmented Assignment Operators](#augmented-assignment-operators)
- [Finding a Value in a List with the index() Method](#finding-a-value-in-a-list-with-the-index-method)
- [Adding Values to Lists with the append() and insert() Methods](#adding-values-to-lists-with-the-append-and-insert-methods)
- [Removing Values from Lists with remove()](#removing-values-from-lists-with-remove)
- [Sorting the Values in a List with the sort() Method](#sorting-the-values-in-a-list-with-the-sort-method)
- [Tuple Data Type](#tuple-data-type)
- [Converting Types with the list() and tuple() Functions](#converting-types-with-the-list-and-tuple-functions)
- [Dictionaries and Structuring Data](#dictionaries-and-structuring-data)
- [The keys(), values(), and items() Methods](#the-keys-values-and-items-methods)
- [Checking Whether a Key or Value Exists in a Dictionary](#checking-whether-a-key-or-value-exists-in-a-dictionary)
- [The get() Method](#the-get-method)
- [The setdefault() Method](#the-setdefault-method)
- [Pretty Printing](#pretty-printing)
- [itertools Module](#itertools-module)
- [accumulate()](#accumulate)
- [combinations()](#combinations)
- [combinations_with_replacement()](#combinationswithreplacement)
- [count()](#count)
- [cycle()](#cycle)
- [chain()](#chain)
- [compress()](#compress)
- [dropwhile()](#dropwhile)
- [filterfalse()](#filterfalse)
- [groupby()](#groupby)
- [islice()](#islice)
- [permutations()](#permutations)
- [product()](#product)
- [repeat()](#repeat)
- [starmap()](#starmap)
- [takewhile()](#takewhile)
- [tee()](#tee)
- [zip_longest()](#ziplongest)
- [Comprehensions](#comprehensions)
- [List comprehension](#list-comprehension)
- [Set comprehension](#set-comprehension)
- [Dict comprehension](#dict-comprehension)
- [Manipulating Strings](#manipulating-strings)
- [Escape Characters](#escape-characters)
- [Raw Strings](#raw-strings)
- [Multiline Strings with Triple Quotes](#multiline-strings-with-triple-quotes)
- [Indexing and Slicing Strings](#indexing-and-slicing-strings)
- [The in and not in Operators with Strings](#the-in-and-not-in-operators-with-strings)
- [The in and not in Operators with list](#the-in-and-not-in-operators-with-list)
- [The upper(), lower(), isupper(), and islower() String Methods](#the-upper-lower-isupper-and-islower-string-methods)
- [The isX String Methods](#the-isx-string-methods)
- [The startswith() and endswith() String Methods](#the-startswith-and-endswith-string-methods)
- [The join() and split() String Methods](#the-join-and-split-string-methods)
- [Justifying Text with rjust(), ljust(), and center()](#justifying-text-with-rjust-ljust-and-center)
- [Removing Whitespace with strip(), rstrip(), and lstrip()](#removing-whitespace-with-strip-rstrip-and-lstrip)
- [Copying and Pasting Strings with the pyperclip Module (need pip install)](#copying-and-pasting-strings-with-the-pyperclip-module-need-pip-install)
- [String Formatting](#string-formatting)
- [% operator](#operator)
- [String Formatting (str.format)](#string-formatting-strformat)
- [Lazy string formatting](#lazy-string-formatting)
- [Formatted String Literals (Python 3.6+)](#formatted-string-literals-python-36)
- [Template Strings](#template-strings)
- [Regular Expressions](#regular-expressions)
- [Matching Regex Objects](#matching-regex-objects)
- [Grouping with Parentheses](#grouping-with-parentheses)
- [Matching Multiple Groups with the Pipe](#matching-multiple-groups-with-the-pipe)
- [Optional Matching with the Question Mark](#optional-matching-with-the-question-mark)
- [Matching Zero or More with the Star](#matching-zero-or-more-with-the-star)
- [Matching One or More with the Plus](#matching-one-or-more-with-the-plus)
- [Matching Specific Repetitions with Curly Brackets](#matching-specific-repetitions-with-curly-brackets)
- [Greedy and Nongreedy Matching](#greedy-and-nongreedy-matching)
- [The findall() Method](#the-findall-method)
- [Making Your Own Character Classes](#making-your-own-character-classes)
- [The Caret and Dollar Sign Characters](#the-caret-and-dollar-sign-characters)
- [The Wildcard Character](#the-wildcard-character)
- [Matching Everything with Dot-Star](#matching-everything-with-dot-star)
- [Matching Newlines with the Dot Character](#matching-newlines-with-the-dot-character)
- [Review of Regex Symbols](#review-of-regex-symbols)
- [Case-Insensitive Matching](#case-insensitive-matching)
- [Substituting Strings with the sub() Method](#substituting-strings-with-the-sub-method)
- [Managing Complex Regexes](#managing-complex-regexes)
- [Handling File and Directory Paths](#handling-file-and-directory-paths)
- [Backslash on Windows and Forward Slash on OS X and Linux](#backslash-on-windows-and-forward-slash-on-os-x-and-linux)
- [The Current Working Directory](#the-current-working-directory)
- [Creating New Folders](#creating-new-folders)
- [Absolute vs. Relative Paths](#absolute-vs-relative-paths)
- [Handling Absolute and Relative Paths](#handling-absolute-and-relative-paths)
- [Checking Path Validity](#checking-path-validity)
- [Finding File Sizes and Folder Contents](#finding-file-sizes-and-folder-contents)
- [Copying Files and Folders](#copying-files-and-folders)
- [Moving and Renaming Files and Folders](#moving-and-renaming-files-and-folders)
- [Permanently Deleting Files and Folders](#permanently-deleting-files-and-folders)
- [Safe Deletes with the send2trash Module](#safe-deletes-with-the-send2trash-module)
- [Walking a Directory Tree](#walking-a-directory-tree)
- [Reading and Writing Files](#reading-and-writing-files)
- [The File Reading/Writing Process](#the-file-readingwriting-process)
- [Opening and reading files with the open() function](#opening-and-reading-files-with-the-open-function)
- [Writing to Files](#writing-to-files)
- [Saving Variables with the shelve Module](#saving-variables-with-the-shelve-module)
- [Saving Variables with the pprint.pformat() Function](#saving-variables-with-the-pprintpformat-function)
- [Reading ZIP Files](#reading-zip-files)
- [Extracting from ZIP Files](#extracting-from-zip-files)
- [Creating and Adding to ZIP Files](#creating-and-adding-to-zip-files)
- [JSON, YAML and configuration files](#json-yaml-and-configuration-files)
- [JSON](#json)
- [YAML](#yaml)
- [Anyconfig](#anyconfig)
- [Debugging](#debugging)
- [Raising Exceptions](#raising-exceptions)
- [Getting the Traceback as a String](#getting-the-traceback-as-a-string)
- [Assertions](#assertions)
- [Logging](#logging)
- [Logging Levels](#logging-levels)
- [Disabling Logging](#disabling-logging)
- [Logging to a File](#logging-to-a-file)
- [Lambda Functions](#lambda-functions)
- [Ternary Conditional Operator](#ternary-conditional-operator)
- [Virtual Environment](#virtual-environment)
- [virtualenv](#virtualenv)
- [pipenv](#pipenv)
## Python Basics
### Math Operators
From **Highest** to **Lowest** precedence:
| Operators | Operation | Example |
| --------- | ---------------- | --------------- |
| ** | Exponent | `2 ** 3 = 8` |
| % | Modulus/Remaider | `22 % 8 = 6` |
| // | Integer division | `22 // 8 = 2` |
| / | Division | `22 / 8 = 2.75` |
| * | Multiplication | `3 * 3 = 9` |
| - | Subtraction | `5 - 2 = 3` |
| + | Addition | `2 + 2 = 4` |
Examples of expressions in the interactive shell:
```python
>>> 2 + 3 * 6
20
```
```python
>>> (2 + 3) * 6
30
```
```python
>>> 2 ** 8
256
```
```python
>>> 23 // 7
3
```
```python
>>> 23 % 7
2
```
```python
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
```
[*Return to the Top*](#python-cheatsheet)
### Data Types
| Data Type | Examples |
| ---------------------- | ----------------------------------------- |
| Integers | `-2, -1, 0, 1, 2, 3, 4, 5` |
| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` |
| Strings | `'a', 'aa', 'aaa', 'Hello!', '11 cats'` |
[*Return to the Top*](#python-cheatsheet)
### String Concatenation and Replication
String concatenation:
```python
>>> 'Alice' 'Bob'
'AliceBob'
```
Note: Avoid `+` operator for string concatenation. Prefer string formatting.
String Replication:
```python
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'
```
[*Return to the Top*](#python-cheatsheet)
### Variables
You can name a variable anything as long as it obeys the following three rules:
1. It can be only one word.
1. It can use only letters, numbers, and the underscore (`_`) character.
1. It can’t begin with a number.
1. Variable name starting with an underscore (`_`) are considered as "unuseful`.
Example:
```python
>>> spam = 'Hello'
>>> spam
'Hello'
```
```python
>>> _spam = 'Hello'
```
`_spam` should not be used again in the code.
[*Return to the Top*](#python-cheatsheet)
### Comments
Inline comment:
```python
# This is a comment
```
Multiline comment:
```Python
# This is a
# multiline comment
```
Code with a comment:
```python
a = 1 # initialization
```
Please note the two spaces in front of the comment.
Function docstring:
```python
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""
```
[*Return to the Top*](#python-cheatsheet)
### The print() Function
```python
>>> print('Hello world!')
Hello world!
```
```python
>>> a = 1
>>> print('Hello world!', a)
Hello world! 1
```
[*Return to the Top*](#python-cheatsheet)
### The input() Function
Example Code:
```python
>>> print('What is your name?') # ask for their name
>>> myName = input()
>>> print('It is good to meet you, {}'.format(myName))
What is your name?
Al
It is good to meet you, Al
```
[*Return to the Top*](#python-cheatsheet)
### The len() Function
Evaluates to the integer value of the number of characters in a string:
```python
>>> len('hello')
5
```
Note: test of emptiness of strings, lists, dictionary, etc, should **not** use len, but prefer direct
boolean evaluation.
```python
>>> a = [1, 2, 3]
>>> if a:
>>> print("the list is not empty!")
```
[*Return to the Top*](#python-cheatsheet)
### The str(), int(), and float() Functions
Integer to String or Float:
```python
>>> str(29)
'29'
```
```python
>>> print('I am {} years old.'.format(str(29)))
I am 29 years old.
```
```python
>>> str(-3.14)
'-3.14'
```
Float to Integer:
```python
>>> int(7.7)
7
```
```python
>>> int(7.7) + 1
8
```
[*Return to the Top*](#python-cheatsheet)
## Flow Control
### Comparison Operators
| Operator | Meaning |
| -------- | ------------------------ |
| `==` | Equal to |
| `!=` | Not equal to |
| `<` | Less than |
| `>` | Greater Than |
| `<=` | Less than or Equal to |
| `>=` | Greater than or Equal to |
These operators evaluate to True or False depending on the values you give them.
Examples:
```python
>>> 42 == 42
True
```
```python
>>> 40 == 42
False
```
```python
>>> 'hello' == 'hello'
True
```
```python
>>> 'hello' == 'Hello'
False
```
```python
>>> 'dog' != 'cat'
True
```
```python
>>> 42 == 42.0
True
```
```python
>>> 42 == '42'
False
```
### Boolean evaluation
Never use `==` or `!=` operator to evaluate boolean operation. Use the `is` or `is not` operators,
or use implicit boolean evaluation.
NO (even if they are valid Python):
```python
>>> True == True
True
```
```python
>>> True != False
True
```
YES (even if they are valid Python):
```python
>>> True is True
True
```
```python
>>> True is not False
True
```
These statements are equivalent:
```Python
>>> if a is True:
>>> pass
>>> if a is not False:
>>> pass
>>> if a:
>>> pass
```
And these as well:
```Python
>>> if a is False:
>>> pass
>>> if a is not True:
>>> pass
>>> if not a:
>>> pass
```
[*Return to the Top*](#python-cheatsheet)
### Boolean Operators
There are three Boolean operators: and, or, and not.
The *and* Operator’s *Truth* Table:
| Expression | Evaluates to |
| ----------------- | ------------ |
| `True and True` | `True` |
| `True and False` | `False` |
| `False and True` | `False` |
| `False and False` | `False` |
The *or* Operator’s *Truth* Table:
| Expression | Evaluates to |
| ---------------- | -------------- |
| `True or True` | `True` |
| `True or False` | `True` |
| `False or True` | `True` |
| `False or False` | `False` |
The *not* Operator’s *Truth* Table:
| Expression | Evaluates to |
| ------------ | ------------- |
| `not True` | `False` |
| `not False` | `True` |
[*Return to the Top*](#python-cheatsheet)
### Mixing Boolean and Comparison Operators
```python
>>> (4 < 5) and (5 < 6)
True
```
```python
>>> (4 < 5) and (9 < 6)
False
```
```python
>>> (1 == 2) or (2 == 2)
True
```
You can also use multiple Boolean operators in an expression, along with the comparison operators:
```python
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
```
[*Return to the Top*](#python-cheatsheet)
### if Statements
```python
if name == 'Alice':
print('Hi, Alice.')
```
[*Return to the Top*](#python-cheatsheet)
### else Statements
```python
name = 'Bob'
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
```
[*Return to the Top*](#python-cheatsheet)
### elif Statements
```python
name = 'Bob'
age = 5
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
```
```python
name = 'Bob'
age = 30
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
```
[*Return to the Top*](#python-cheatsheet)
### while Loop Statements
```python
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
```
[*Return to the Top*](#python-cheatsheet)
### break Statements
If the execution reaches a break statement, it immediately exits the while loop’s clause:
```python
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
```
[*Return to the Top*](#python-cheatsheet)
### continue Statements
When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.
```python
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
```
[*Return to the Top*](#python-cheatsheet)
### for Loops and the range() Function
```python
>>> print('My name is')
>>> for i in range(5):
>>> print('Jimmy Five Times ({})'.format(str(i)))
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
```
The *range()* function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.
```python
>>> for i in range(0, 10, 2):
>>> print(i)
0
2
4
6
8
```
You can even use a negative number for the step argument to make the for loop count down instead of up.
```python
>>> for i in range(5, -1, -1):
>>> print(i)
5
4
3
2
1
0
```
### For else statement
This allows to specify a statement to execute in case of the full loop has been executed. Only
useful when a `break` condition can occur in the loop:
```python
>>> for i in [1, 2, 3, 4, 5]:
>>> if i == 3:
>>> break
>>> else:
>>> print("only executed when no item of the list is equal to 3")
```
[*Return to the Top*](#python-cheatsheet)
### Importing Modules
```python
import random
for i in range(5):
print(random.randint(1, 10))
```
```python
import random, sys, os, math
```
```python
from random import *.
```
[*Return to the Top*](#python-cheatsheet)
### Ending a Program Early with sys.exit()
```python
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed {}.'.format(response))
```
[*Return to the Top*](#python-cheatsheet)
## Functions
```python
>>> def hello(name):
>>> print('Hello {}'.format(name))
>>>
>>> hello('Alice')
>>> hello('Bob')
Hello Alice
Hello Bob
```
[*Return to the Top*](#python-cheatsheet)
### Return Values and return Statements
When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:
- The return keyword.
- The value or expression that the function should return.
```python
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)
```
[*Return to the Top*](#python-cheatsheet)
### The None Value
```python
>>> spam = print('Hello!')
Hello!
```
```python
>>> spam is None
True
```
Note: never compare to `None` with the `==` operator. Always use `is`.
[*Return to the Top*](#python-cheatsheet)
### Keyword Arguments and print()
```python
>>> print('Hello', end='')
>>> print('World')
HelloWorld
```
```python
>>> print('cats', 'dogs', 'mice')
cats dogs mice
```
```python
>>> print('cats', 'dogs', 'mice', sep=',')
cats,dogs,mice
```
[*Return to the Top*](#python-cheatsheet)
### Local and Global Scope
- Code in the global scope cannot use any local variables.
- However, a local scope can access global variables.
- Code in a function’s local scope cannot use variables in any other local scope.
- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.
[*Return to the Top*](#python-cheatsheet)
### The global Statement
If you need to modify a global variable from within a function, use the global statement:
```python
>>> def spam():
>>> global eggs
>>> eggs = 'spam'
>>>
>>> eggs = 'global'
>>> spam()
>>> print(eggs)
spam
```
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
1. If there is a global statement for that variable in a function, it is a global variable.
1. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
1. But if the variable is not used in an assignment statement, it is a global variable.
[*Return to the Top*](#python-cheatsheet)
## Exception Handling
### Basic exception handling
```python
>>> def spam(divideBy):
>>> try:
>>> return 42 / divideBy
>>> except ZeroDivisionError as e:
>>> print('Error: Invalid argument: {}'.format(e))
>>>
>>> print(spam(2))
>>> print(spam(12))
>>> print(spam(0))
>>> print(spam(1))
21.0
3.5
Error: Invalid argument: division by zero
None
42.0
```
[*Return to the Top*](#python-cheatsheet)
### Final code in exception handling
Code inside the `finally` section is always executed, no matter if an exception has been raised or
not, and even if an exception is not caught.
```python
>>> def spam(divideBy):
>>> try:
>>> return 42 / divideBy
>>> except ZeroDivisionError as e:
>>> print('Error: Invalid argument: {}'.format(e))
>>> finally:
>>> print("-- division finished --")
>>> print(spam(12))
>>> print(spam(0))
21.0
-- division finished --
3.5
-- division finished --
Error: Invalid argument: division by zero
-- division finished --
None
-- division finished --
42.0
-- division finished --
```
[*Return to the Top*](#python-cheatsheet)
## Lists
```python
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
```
[*Return to the Top*](#python-cheatsheet)
### Getting Individual Values in a List with Indexes
```python
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
```
```python
>>> spam[1]
'bat'
```
```python
>>> spam[2]
'rat'
```
```python
>>> spam[3]
'elephant'
```
[*Return to the Top*](#python-cheatsheet)
### Negative Indexes
```python
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[-1]
'elephant'
```
```python
>>> spam[-3]
'bat'
```
```python
>>> 'The {} is afraid of the {}.'.format(spam[-1], spam[-3])
'The elephant is afraid of the bat.'
```
[*Return to the Top*](#python-cheatsheet)
### Getting Sublists with Slices
```python
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
```
```python
>>> spam[1:3]
['bat', 'rat']
```
```python
>>> spam[0:-1]
['cat', 'bat', 'rat']
```