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:
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
OperatorMeaningUsage+Addition or unary plusx + y-Subtraction or unary minusx - y*Multiplicationx * y/Division (result is always a float)x / y%Modulusx % y (remainder of x/y)//Floor division - results into whole number (may be float)x // y**Exponentx**y (x to the power y)
5. Python Operators Precedence Table
OperatorDescription**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 operatorsis , is notIdentity operatorsin not inMembership operatorsnot , or , andLogical operators
6.Python Relational Operators
OperatorMeaningUsage>Greater thanx > y<Less thanx < y==Equal tox == y!=Not equal tox != y>=Greater than or equal tox >= y<=Less than or equal to x <= y
7.Python Logical Operators
OperatorMeaningUsageandTrue if both the operands are truex and yorTrue if either of the operands is truex or ynotcomplements the operandnot 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 notoperator flips the value of the Boolean operand. It converts True to False and False to True.
Anot ATrueFalseFalseTrue
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.
ABA and BTrueTrueTrueTrueFalseFalseFalseTrueFalseFalseFalseFalse
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.
ABA or BTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalse
9.Python Membership Operators
OperatorMeaningUsageinCheck to see if value is in the sequence5 in [2,5,3,7]not inCheck to see if value is not in the sequence5 not in [2,5,3,7]
10.Complete Precedence Table
The following table shows the complete precedence of Python Operators: Highest to Lowest
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
2
SP 0020 32
! 0021 33
" 0022 34
# 0023 35
$ 0024 36
% 0025 37
& 0026 38
' 0027 39
( 0028 40
) 0029 41
* 002A 42
+ 002B 43
, 002C 44
- 002D 45
. 002E 46
/ 002F 47
3
0 0030 48
1 0031 49
2 0032 50
3 0033 51
4 0034 52
5 0035 53
6 0036 54
7 0037 55
8 0038 56
9 0039 57
: 003A 58
; 003B 59
< 003C 60
= 003D 61
> 003E 62
? 003F 63
4
@ 0040 64
A 0041 65
B 0042 66
C 0043 67
D 0044 68
E 0045 69
F 0046 70
G 0047 71
H 0048 72
I 0049 73
J 004A 74
K 004B 75
L 004C 76
M 004D 77
N 004E 78
O 004F 79
5
P 0050 80
Q 0051 81
R 0052 82
S 0053 83
T 0054 84
U 0055 85
V 0056 86
W 0057 87
X 0058 88
Y 0059 89
Z 005A 90
[ 005B 91
\ 005C 92
] 005D 93
^ 005E 94
_ 005F 95
6
` 0060 96
a 0061 97
b 0062 98
c 0063 99
d 0064 100
e 0065 101
f 0066 102
g 0067 103
h 0068 104
i 0069 105
j 006A 106
k 006B 107
l 006C 108
m 006D 109
n 006E 110
o 006F 111
7
p 0070 112
q 0071 113
r 0072 114
s 0073 115
t 0074 116
u 0075 117
v 0076 118
w 0077 119
x 0078 120
y 0079 121
z 007A 122
{ 007B 123
| 007C 124
} 007D 125
~ 007E 126
DEL 007F 127
14.Table of ASCII Control Characters
DecimalHexadecimalBinaryCharacterDescription000NULnull111SOHstart of header2210STXstart of text3311ETXend of text44100EOTend of transmission55101ENQenquiry66110ACKacknowledge77111BELbell881000BSbackspace991001HThorizontal tab100A1010LFline feed110B1011VTvertical tab120C1100FFform feed130D1101CRenter / carriage return140E1110SOshift out150F1111SIshift in161010000DLEdata link escape171110001DC1device control 1181210010DC2device control 2191310011DC3device control 3201410100DC4device control 4211510101NAKnegative acknowledge221610110SYNsynchronize231710111ETBend of trans. block241811000CANcancel251911001EMend of medium261A11010SUBsubstitute271B11011 ESCescape281C11100 FSfile separator291D11101GSgroup separator301E11110RSrecord separator311F11111USunit separator
Method Descriptions.capitalize()The first character of s is put in uppercases.center([width])Centers s in a field of length widths.count(sub [,start [, end]])Counts occurrences of sub between start and ends.encode([encoding [, errors]])Encode s using encoding as code and errors.expandtabs([tabsize])Expands tabss.find(sub [, start [, end]])Finds the first occurrence of sub between start and ends.index(sub [,start [, end]])same as find but raises an exception if no occurrence is founds.islower()Returns True if all chracters are lowercase, False otherwises.isupper()Returns True if all chracters are uppercase, False otherwises.join(words)Joins the list of words with s as delimiters.ljust(width)Left align s in a string of length widths.lower()Returns a lowercase version of ss.lstrip()Removes all leading whitespace characters of ss.replace(old, new [, maxrep])Replace maximal maxrep versions of substring old with substring news.rfind(sub [, start [, end]])Finds the last occurrence of substring sub between start and ends.rindex(sub [,start [, end]])Same as rfind but raise an exception if sub does not existss.rjust(width)Right-align s in a string of length widths.rstrip()Removes trailing whitespace characterss.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 newlines.strip()Removes trailing and leading whitespace characterss.swapcase()Returns a copy of s with lowercase letters turn into uppercase and vice versas.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
Descriptiondict.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 dictionarydict.items()Returns a view object of dict items.dict.keys()Returns a view object of dict keys.dict.pop(key)Remove key, Return valuedict.setdefault(key, default=None)Similar to get(), but will set dict[key]=default if key is not already in dictdict.update(dict2)Adds dictionary dict2's key-values pairs to dictdict.values()Returns a view object of dict_values.
18.File access Modes
File access Modes
ModeDescriptionrOpens a file for reading only. This is the default mode.rbOpens a file for reading only in binary formatr+Opens a file for both reading and writing. rb+Opens a file for both reading and writing in binary format. wOpens a file for writing only. Overwrites the file if the file exists. Create a new file if it does not exist.wbOpens 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. aOpens a file for appending. The file pointer is at the end of the file if the file exists. abOpens 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 FunctionsDescriptionopen()returns a file object, and is most commonly used with two arguments: open(filename, mode).file.close()Close the filefile.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 filefile.seek()Changes the file object’s position
20.String Formatting
String Formatting
SymbolDescriptionbFormat an integer in binary. cGiven a number, display the character that has that code. dDisplay a number in decimal (base 10). eDisplay a float value using the exponential format. ESame as e, but use a capital “E” in the exponent. fFormat a number in fixed-point form. gGeneral numeric format: use either f or g, whichever is appropriate. GSame as “g”, but uses a capital “E” in the exponential form. nFor formatting numbers, this format uses the current local setting to insert separator characters.oDisplay an integer in octal format. xDisplay an integer in hexadecimal (base 16). Digits greater than 9 are displayed as lowercase characters. XDisplay 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.142 decimal places 3.1415926{:+.2f} 3.142 decimal places with sign -1{:+.2f} -12 decimal places with sign 2.71828{:.0f} 3No decimal places 5{:0>2d} 5Pad 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,000Number format with comma separator 0.25{:.2%} 25.00%Format percentage 1E+09{:.2e} 1.00E+09Exponent notation 13{:10d} 13Right aligned (default, width 10) 13{:<10d} 13Left aligned (width 10)13{:^10d} 13 Center aligned (width 10)
22. Standard Exceptions
EXCEPTION NAMEDESCRIPTIONArithmeticErrorBase class for all errors that occur for numeric calculation.AssertionErrorRaised in case of failure of the Assert statement.AttributeErrorRaised in case of failure of attribute reference or assignment.EnvironmentErrorBase class for all exceptions that occur outside the Python environment.EOFErrorRaised when there is no input from either the raw_input() or input() function and the end of file is reached.ExceptionBase class for all exceptionsFloatingPointErrorRaised when a floating point calculation fails.ImportErrorRaised when an import statement fails.IndentationErrorRaised when indentation is not specified properly.IndexErrorRaised when an index is not found in a sequence.IOErrorRaised 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.IOErrorRaised for operating system-related errors.KeyboardInterruptRaised when the user interrupts program execution, usually by pressing Ctrl+c.KeyErrorRaised when the specified key is not found in the dictionary.LookupErrorBase class for all lookup errors.NameErrorRaised when an identifier is not found in the local or global namespace.NotImplementedErrorRaised when an abstract method that needs to be implemented in an inherited class is not actually implemented.OverflowErrorRaised 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.RuntimeErrorRaised when a generated error does not fall into any category.StandardErrorBase class for all built-in exceptions except StopIteration and SystemExit.StopIterationRaised when the next() method of an iterator does not point to any object.SyntaxErrorRaised when there is an error in Python syntax.SystemErrorRaised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.SystemExitRaised by the sys.exit() function.SystemExitRaised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.UnboundLocalErrorRaised when trying to access a local variable in a function or method but no value has been assigned to it.ValueErrorRaised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.ZeroDivisonErrorRaised when division or modulo by zero takes place for all numeric types.