1.Keywords
Keywords
Keywords are special words that are reserved by Python and cannot be used by you to name things. They indicate commands to the Python interpreter. The following is a complete list of Python keywords:
and | del | from | not | while |
as | elif | global | or | with |
assert | else | if | pass | yield |
break | except | import | nonlocal | class |
lambda | in | raise | continue | finally |
is | return | def | for | |
try | True | False | None | |
2. Operators
Operators
Operators are special tokens (sequence of characters) that have meaning to the Python Interpreter. Using them implies some form of mathematical operation. The following is the complete list of Operators.
( | ) | [ | ] | { | } |
, | : | . | ` | = | ; |
' | '' | # | \ | @ | |
3. Punctuators and Delimiters
Punctuators and Delimiters
Punctuators which are also known as delimiters, separate different elements in Python statements and expressions. Here is the complete list:
( | ) | [ | ] | { | } |
, | : | . | ` | = | ; |
' | '' | # | \ | @ | |
4.Python Arithmetic Operators
Operator | Meaning | Usage |
+ | Addition or unary plus | x + y |
- | Subtraction or unary minus | x - y |
* | Multiplication | x * y |
/ | Division (result is always a float) | x / y |
% | Modulus | x % y (remainder of x/y) |
// | Floor division - results into whole number (may be float) | x // y |
** | Exponent | x**y (x to the power y) |
5. Python Operators Precedence Table
Operator | Description |
** | Exponentiation |
~, +, - | Complement, unary plus and unary minus |
*, /, %, // | Multiply, divide, modulo and whole (floor) division |
+, - | Addition and subtraction |
>>, << | Right and left bitwise shift |
& | Bitwise and |
^ ,| | Bitwise exclusive or and bitwise or |
<=, < ,> ,>=, | Relational operators |
<> ,== ,!= | Equality operators |
= ,%= ,/= ,//= ,-= ,+= ,*=, **= | Assignment operators |
is , is not | Identity operators |
in not in | Membership operators |
not , or , and | Logical operators |
6.Python Relational Operators
Operator | Meaning | Usage |
> | Greater than | x > y |
< | Less than | x < y |
== | Equal to | x == y |
!= | Not equal to | x != y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
7.Python Logical Operators
Operator | Meaning | Usage |
and | True if both the operands are true | x and y |
or | True if either of the operands is true | x or y |
not | complements the operand | not x |
8.Boolean Operators
The basic Boolean operators are: and, or, not . The following is the truth table for each of these operators. Note that A and B in the tables below are the names of the operands that represent a Boolean Expression.
not A
The not operator flips the value of the Boolean operand. It converts True to False and False to True.
A | not A |
True | False |
False | True |
A and B
The and operator requires both A and B to be True for the whole expression to be True. If only one of them isFalse then the entire expression is False.
A | B | A and B |
True | True | True |
True | False | False |
False | True | False |
False | False | False |
A or B
The or operator only requires one of A or B to be True for the entire expression to be True. The whole expression is False only when neither A nor B is True.
A | B | A or B |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
9.Python Membership Operators
Operator | Meaning | Usage |
in | Check to see if value is in the sequence | 5 in [2,5,3,7] |
not in | Check to see if value is not in the sequence | 5 not in [2,5,3,7] |
10.Complete Precedence Table
The following table shows the complete precedence of Python Operators: Highest to Lowest
OPERATOR | DESCRIPTION |
() | Parenthesis (grouping) |
f(args...), x[i:i], x[i], x.attr | Function call, slicing, subscript, dot |
** | Exponentiation |
+, -, ~ | Unary Positive, Unary Negative, bitwise NOT |
*, /, % | Multiplication, Division, Remainder |
+, - | Addition, Subtraction |
<<, >> | Shifts |
& | Bitwise AND |
^ | Bitwise XOR |
| | Bitwise OR |
<, <=, >, >=, !=, ==, is, is not, in, not in | Comparisons, identity, membership |
not | Boolean NOT |
and | Boolean AND |
or | Boolean OR |
lambda | Lambda Expression |
11.Built-in Functions
The python interpreter has a number of functions built into it that are always available.
For more information on Built-in Functions, you may look at the Python Documentation.
12.common list method
Table of common methods for lists
list.append(x) | Add an item to the end of the list. Equivalent to a[len(a):] = [x]. |
list.extend(L) | Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L. |
list.insert(i, x) | Insert an item at a given position. The first argument is the index of the element to insert. |
list.remove(x) | Remove the first item from the list whose value is x. It is an error if there is no such item. |
list.copy() | Return a shallow copy of the list. Equivalent to a[:]. |
list.pop([i]) | Remove the item at the given position and return it. If no index is specified, removes the last item. |
list.clear() | Remove all items from the list. Equivalent to del a[:]. |
list.index(x) | Return the index in the list of the first item whose value is x. It is an error if there is no such item. |
list.count(x) | Return the number of times x appears in the list. |
list.reverse() | Reverse the elements of the list in place. |
list.sort(key=None, reverse=False) | Sort the items of the list in place (the arguments can be used for sort customization). |
13.Most commonly used UTF-8 Character Codes
Source: wiki
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | |
| SP | ! | " | # | $ | % | & | ' | ( | ) | * | + | , | - | . | / |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | : | ; | < | = | > | ? |
| @ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O |
| P | Q | R | S | T | U | V | W | X | Y | Z | [ | \ | ] | ^ | _ |
| ` | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o |
| p | q | r | s | t | u | v | w | x | y | z | { | | | } | ~ | DEL |
14.Table of ASCII Control Characters
Decimal | Hexadecimal | Binary | Character | Description |
0 | 0 | 0 | NUL | null |
1 | 1 | 1 | SOH | start of header |
2 | 2 | 10 | STX | start of text |
3 | 3 | 11 | ETX | end of text |
4 | 4 | 100 | EOT | end of transmission |
5 | 5 | 101 | ENQ | enquiry |
6 | 6 | 110 | ACK | acknowledge |
7 | 7 | 111 | BEL | bell |
8 | 8 | 1000 | BS | backspace |
9 | 9 | 1001 | HT | horizontal tab |
10 | 0A | 1010 | LF | line feed |
11 | 0B | 1011 | VT | vertical tab |
12 | 0C | 1100 | FF | form feed |
13 | 0D | 1101 | CR | enter / carriage return |
14 | 0E | 1110 | SO | shift out |
15 | 0F | 1111 | SI | shift in |
16 | 10 | 10000 | DLE | data link escape |
17 | 11 | 10001 | DC1 | device control 1 |
18 | 12 | 10010 | DC2 | device control 2 |
19 | 13 | 10011 | DC3 | device control 3 |
20 | 14 | 10100 | DC4 | device control 4 |
21 | 15 | 10101 | NAK | negative acknowledge |
22 | 16 | 10110 | SYN | synchronize |
23 | 17 | 10111 | ETB | end of trans. block |
24 | 18 | 11000 | CAN | cancel |
25 | 19 | 11001 | EM | end of medium |
26 | 1A | 11010 | SUB | substitute |
27 | 1B | 11011 | ESC | escape |
28 | 1C | 11100 | FS | file separator |
29 | 1D | 11101 | GS | group separator |
30 | 1E | 11110 | RS | record separator |
31 | 1F | 11111 | US | unit separator |
15.Table of printable ASCII Characters
Decimal | Hexadecimal | Binary | Character | Description |
32 | 20 | 100000 | Space | space |
33 | 21 | 100001 | ! | exclamation mark |
34 | 22 | 100010 | " | double quote |
35 | 23 | 100011 | # | number |
36 | 24 | 100100 | $ | dollar |
37 | 25 | 100101 | % | percent |
38 | 26 | 100110 | & | ampersand |
39 | 27 | 100111 | ' | single quote |
40 | 28 | 101000 | ( | left parenthesis |
41 | 29 | 101001 | ) | right parenthesis |
42 | 2A | 101010 | * | asterisk |
43 | 2B | 101011 | + | plus |
44 | 2C | 101100 | , | comma |
45 | 2D | 101101 | - | minus |
46 | 2E | 101110 | . | period |
47 | 2F | 101111 | / | slash |
48 | 30 | 110000 | 0 | zero |
49 | 31 | 110001 | 1 | one |
50 | 32 | 110010 | 2 | two |
51 | 33 | 110011 | 3 | three |
52 | 34 | 110100 | 4 | four |
53 | 35 | 110101 | 5 | five |
54 | 36 | 110110 | 6 | six |
55 | 37 | 110111 | 7 | seven |
56 | 38 | 111000 | 8 | eight |
57 | 39 | 111001 | 9 | nine |
58 | 3A | 111010 | : | colon |
59 | 3B | 111011 | ; | semicolon |
60 | 3C | 111100 | < | less than |
61 | 3D | 111101 | = | equality sign |
62 | 3E | 111110 | > | greater than |
63 | 3F | 111111 | ? | question mark |
64 | 40 | 1000000 | @ | at sign |
65 | 41 | 1000001 | A | |
66 | 42 | 1000010 | B | |
67 | 43 | 1000011 | C | |
68 | 44 | 1000100 | D | |
69 | 45 | 1000101 | E | |
70 | 46 | 1000110 | F | |
71 | 47 | 1000111 | G | |
72 | 48 | 1001000 | H | |
73 | 49 | 1001001 | I | |
74 | 4A | 1001010 | J | |
75 | 4B | 1001011 | K | |
76 | 4C | 1001100 | L | |
77 | 4D | 1001101 | M | |
78 | 4E | 1001110 | N | |
79 | 4F | 1001111 | O | |
80 | 50 | 1010000 | P | |
81 | 51 | 1010001 | Q | |
82 | 52 | 1010010 | R | |
83 | 53 | 1010011 | S | |
84 | 54 | 1010100 | T | |
85 | 55 | 1010101 | U | |
86 | 56 | 1010110 | V | |
87 | 57 | 1010111 | W | |
88 | 58 | 1011000 | X | |
89 | 59 | 1011001 | Y | |
90 | 5A | 1011010 | Z | |
91 | 5B | 1011011 | [ | left square bracket |
92 | 5C | 1011100 | \ | backslash |
93 | 5D | 1011101 | ] | right square bracket |
94 | 5E | 1011110 | ^ | caret / circumflex |
95 | 5F | 1011111 | _ | underscore |
96 | 60 | 1100000 | ` | grave / accent |
97 | 61 | 1100001 | a | |
98 | 62 | 1100010 | b | |
99 | 63 | 1100011 | c | |
100 | 64 | 1100100 | d | |
101 | 65 | 1100101 | e | |
102 | 66 | 1100110 | f | |
103 | 67 | 1100111 | g | |
104 | 68 | 1101000 | h | |
105 | 69 | 1101001 | i | |
106 | 6A | 1101010 | j | |
107 | 6B | 1101011 | k | |
108 | 6C | 1101100 | l | |
109 | 6D | 1101101 | m | |
110 | 6E | 1101110 | n | |
111 | 6F | 1101111 | o | |
112 | 70 | 1110000 | p | |
113 | 71 | 1110001 | q | |
114 | 72 | 1110010 | r | |
115 | 73 | 1110011 | s | |
116 | 74 | 1110100 | t | |
117 | 75 | 1110101 | u | |
118 | 76 | 1110110 | v | |
119 | 77 | 1110111 | w | |
120 | 78 | 1111000 | x | |
121 | 79 | 1111001 | y | |
122 | 7A | 1111010 | z | |
123 | 7B | 1111011 | { | left curly bracket |
124 | 7C | 1111100 | | | vertical bar |
125 | 7D | 1111101 | } | right curly bracket |
126 | 7E | 1111110 | ~ | tilde |
127 | 7F | 1111111 | DEL | delete |
16.string methods
Method | Description |
s.capitalize() | The first character of s is put in uppercase |
s.center([width]) | Centers s in a field of length width |
s.count(sub [,start [, end]]) | Counts occurrences of sub between start and end |
s.encode([encoding [, errors]]) | Encode s using encoding as code and error |
s.expandtabs([tabsize]) | Expands tabs |
s.find(sub [, start [, end]]) | Finds the first occurrence of sub between start and end |
s.index(sub [,start [, end]]) | same as find but raises an exception if no occurrence is found |
s.islower() | Returns True if all chracters are lowercase, False otherwise |
s.isupper() | Returns True if all chracters are uppercase, False otherwise |
s.join(words) | Joins the list of words with s as delimiter |
s.ljust(width) | Left align s in a string of length width |
s.lower() | Returns a lowercase version of s |
s.lstrip() | Removes all leading whitespace characters of s |
s.replace(old, new [, maxrep]) | Replace maximal maxrep versions of substring old with substring new |
s.rfind(sub [, start [, end]]) | Finds the last occurrence of substring sub between start and end |
s.rindex(sub [,start [, end]]) | Same as rfind but raise an exception if sub does not exists |
s.rjust(width) | Right-align s in a string of length width |
s.rstrip() | Removes trailing whitespace characters |
s.split([sep [, maxsplit]])) | Split s into maximal maxsplit words using sep as separator (default whitespace) |
s.splitlines([keepends]) | Split s into lines, if keepends is 1 keep the trailing newline |
s.strip() | Removes trailing and leading whitespace characters |
s.swapcase() | Returns a copy of s with lowercase letters turn into uppercase and vice versa |
s.title() | Returns a title-case version of s (all words capitalized) |
s.upper() | Returns an uppercase version of s |
17.common methods for Dictionaries
Table of common methods for Dictionaries
Method Name | Description |
dict.clear() | Removes all elements of dictionary. |
dict.copy() | Returns a shallow copy of dictionary. |
dict.fromkeys(seq[,value]) | Create a new dictionary with keys from seq and values set to value. |
dict.get(key, default=None) | For key key, returns value or default if key not in dictionary |
dict.items() | Returns a view object of dict items. |
dict.keys() | Returns a view object of dict keys. |
dict.pop(key) | Remove key, Return value |
dict.setdefault(key, default=None) | Similar to get(), but will set dict[key]=default if key is not already in dict |
dict.update(dict2) | Adds dictionary dict2's key-values pairs to dict |
dict.values() | Returns a view object of dict_values. |
18.File access Modes
File access Modes
Mode | Description |
r | Opens a file for reading only. This is the default mode. |
rb | Opens a file for reading only in binary format |
r+ | Opens a file for both reading and writing. |
rb+ | Opens a file for both reading and writing in binary format. |
w | Opens a file for writing only. Overwrites the file if the file exists. Create a new file if it does not exist. |
wb | Opens a file for writing only in binary format. |
w+ | Opens a file for both writing and reading. Overwrites the file if the file exists. Create a new file if it does not exist. |
wb+ | Opens a file for both writing and reading in binary format. |
a | Opens a file for appending. The file pointer is at the end of the file if the file exists. |
ab | Opens a file for appending in binary format. |
a+ | Opens a file for both appending and reading. |
ab+ | Opens a file for both appending and reading in binary format. |
19. Common File Methods
Common File Functions and Methods
Methods and Functions | Description |
open() | returns a file object, and is most commonly used with two arguments: open(filename, mode). |
file.close() | Close the file |
file.read([size]) | Read entire file. If size is specified then read at most size bytes. |
file.readline([size]) | Read one line from file. If size is specified then read at most size bytes. |
file.readlines([size]) | Read all the lines from the file and return a list of lines. If size is specified then read at most size bytes. |
file.write() | Writes the contents of string to the file, returning the number of characters written. |
file.tell() | Returns an integer giving the file object’s current position in the file |
file.seek() | Changes the file object’s position |
20.String Formatting
String Formatting
Symbol | Description |
b | Format an integer in binary. |
c | Given a number, display the character that has that code. |
d | Display a number in decimal (base 10). |
e | Display a float value using the exponential format. |
E | Same as e, but use a capital “E” in the exponent. |
f | Format a number in fixed-point form. |
g | General numeric format: use either f or g, whichever is appropriate. |
G | Same as “g”, but uses a capital “E” in the exponential form. |
n | For formatting numbers, this format uses the current local setting to insert separator characters. |
o | Display an integer in octal format. |
x | Display an integer in hexadecimal (base 16). Digits greater than 9 are displayed as lowercase characters. |
X | Display an integer in hexadecimal (base 16). Digits greater than 9 are displayed as uppercase characters. |
% | Display a number as a percentage: its value is multiplied by 100, followed by a “%” character. |
21.String Formatting Example
String Formatting Example Table
Number | Format | Output | Description |
3.1415926 | {:.2f} | 3.14 | 2 decimal places |
3.1415926 | {:+.2f} | 3.14 | 2 decimal places with sign |
-1 | {:+.2f} | -1 | 2 decimal places with sign |
2.71828 | {:.0f} | 3 | No decimal places |
5 | {:0>2d} | 5 | Pad number with zeros (left padding, width 2) |
5 | {:x<4d} | 5xxx | Pad number with x's (right padding, width 4) |
10 | {:x<4d} | 10xx | Pad number with x's (right padding, width 4) |
1000000 | {:,} | 1,000,000 | Number format with comma separator |
0.25 | {:.2%} | 25.00% | Format percentage |
1E+09 | {:.2e} | 1.00E+09 | Exponent notation |
13 | {:10d} | 13 | Right aligned (default, width 10) |
13 | {:<10d} | 13 | Left aligned (width 10) |
13 | {:^10d} | 13 | Center aligned (width 10) |
22. Standard Exceptions
EXCEPTION NAME | DESCRIPTION |
ArithmeticError | Base class for all errors that occur for numeric calculation. |
AssertionError | Raised in case of failure of the Assert statement. |
AttributeError | Raised in case of failure of attribute reference or assignment. |
EnvironmentError | Base class for all exceptions that occur outside the Python environment. |
EOFError | Raised when there is no input from either the raw_input() or input() function and the end of file is reached. |
Exception | Base class for all exceptions |
FloatingPointError | Raised when a floating point calculation fails. |
ImportError | Raised when an import statement fails. |
IndentationError | Raised when indentation is not specified properly. |
IndexError | Raised when an index is not found in a sequence. |
IOError | Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. |
IOError | Raised for operating system-related errors. |
KeyboardInterrupt | Raised when the user interrupts program execution, usually by pressing Ctrl+c. |
KeyError | Raised when the specified key is not found in the dictionary. |
LookupError | Base class for all lookup errors. |
NameError | Raised when an identifier is not found in the local or global namespace. |
NotImplementedError | Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. |
OverflowError | Raised when a calculation exceeds maximum limit for a numeric type. |
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. | Raised when an operation or function is attempted that is invalid for the specified data type. |
RuntimeError | Raised when a generated error does not fall into any category. |
StandardError | Base class for all built-in exceptions except StopIteration and SystemExit. |
StopIteration | Raised when the next() method of an iterator does not point to any object. |
SyntaxError | Raised when there is an error in Python syntax. |
SystemError | Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. |
SystemExit | Raised by the sys.exit() function. |
SystemExit | Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. |
UnboundLocalError | Raised when trying to access a local variable in a function or method but no value has been assigned to it. |
ValueError | Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. |
ZeroDivisonError | Raised when division or modulo by zero takes place for all numeric types. |