Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with Python under the Creative Commons license and many other sources.
From the PEP 20 -- The Zen of Python:
Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.
import thisFrom 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:
2 + 3 * 6(2 + 3) * 62 ** 823 // 723 % 7(5 - 1) * ((7 + 1) / (3 - 1))| 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' |
String concatenation:
'Alice' 'Bob'Note: Avoid + operator for string concatenation. Prefer string formatting.
String Replication:
'Alice' * 5You can name a variable anything as long as it obeys the following rules:
- It can be only one word.
- It can use only letters, numbers, and the underscore (
_) character. - It can’t begin with a number.
- Variable name starting with an underscore (
_) are considered as "unuseful`.
Example:
spam = 'Hello'_spam = 'Hello'_spam should not be used again in the code.
Inline comment:
# This is a commentMultiline comment:
# This is a
# multiline commentCode with a comment:
a = 1 # initializationPlease note the two spaces in front of the comment.
Function docstring:
def foo():
"""
This is a function docstring
You can also use:
''' Function Docstring '''
"""print('Hello world!')a = 1
print('Hello world!', a)Example Code:
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, {}'.format(myName))Evaluates to the integer value of the number of characters in a string:
len('hello')Note: test of emptiness of strings, lists, dictionary, etc, should not use len, but prefer direct boolean evaluation.
a = [1, 2, 3]
if a:
print("the list is not empty!")Integer to String or Float:
str(29)print('I am {} years old.'.format(str(29)))str(-3.14)Float to Integer:
int(7.7)int(7.7) + 1