Quick-Reference
Python Cheat Sheets
Comprehensive Python Cheatsheet
Methods
String Methods
Note: All string methods returns new values. They do not change the original string.
<str> = <str>.strip() # Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split() # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_strings>) # Joins elements using string as a separator.
<bool> = <sub_str> in <str> # Checks if string contains the substring.
<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
<int> = <str>.find(<sub_str>) # Returns start index of the first match or -1.
<int> = <str>.index(<sub_str>) # Same, but raises ValueError if there's no match.
<str> = <str>.lower() # Changes the case. Also upper/capitalize/title().
<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
<str> = <str>.translate(<table>) # Use `str.maketrans(<dict>)` to generate table.
<str> = chr(<int>) # Converts int to Unicode character.
<int> = ord(<str>) # Converts Unicode character to int.
Property Methods
<bool> = <str>.isdecimal() # Checks for [0-9]. Also [०-९] and [٠-٩].
<bool> = <str>.isdigit() # Checks for [²³¹…] and isdecimal().
<bool> = <str>.isnumeric() # Checks for [¼½¾…], [零〇一…] and isdigit().
<bool> = <str>.isalnum() # Checks for [a-zA-Z…] and isnumeric().
<bool> = <str>.isprintable() # Checks for [ !#$%…] and isalnum().
<bool> = <str>.isspace() # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…].
Regex
import re
<str> = re.sub(r'<regex>', new, text, count=0) # Substitutes all occurrences with 'new'.
<list> = re.findall(r'<regex>', text) # Returns all occurrences as strings.
<list> = re.split(r'<regex>', text, maxsplit=0) # Add brackets around regex to keep matches.
<Match> = re.search(r'<regex>', text) # First occurrence of the pattern or None.
<Match> = re.match(r'<regex>', text) # Searches only at the beginning of the text.
<iter> = re.finditer(r'<regex>', text) # Returns all occurrences as Match objects.
Match Object
<str> = <Match>.group() # Returns the whole match. Also group(0).
<str> = <Match>.group(1) # Returns part inside the first brackets.
<tuple> = <Match>.groups() # Returns all bracketed parts.
<int> = <Match>.start() # Returns start index of the match.
<int> = <Match>.end() # Returns exclusive end index of the match.
Special Sequences
'\d' == '[0-9]' # Also [०-९…]. Matches a decimal character.
'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches an alphanumeric or _.
'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches a whitespace.
Method | Description |
---|---|
capitalize() | Converts the first character to upper case |
casefold() | Converts string into lower case |
center() | Returns a centered string |
count() | Returns the number of times a specified value occurs in a string |
encode() | Returns an encoded version of the string |
endswith() | Returns true if the string ends with the specified value |
expandtabs() | Sets the tab size of the string |
find() | Searches the string for a specified value and returns the position of where it was found |
format() | Formats specified values in a string |
format_map() | Formats specified values in a string |
index() | Searches the string for a specified value and returns the position of where it was found |
isalnum() | Returns True if all characters in the string are alphanumeric |
isalpha() | Returns True if all characters in the string are in the alphabet |
isascii() | Returns True if all characters in the string are ascii characters |
isdecimal() | Returns True if all characters in the string are decimals |
isdigit() | Returns True if all characters in the string are digits |
isidentifier() | Returns True if the string is an identifier |
islower() | Returns True if all characters in the string are lower case |
isnumeric() | Returns True if all characters in the string are numeric |
isprintable() | Returns True if all characters in the string are printable |
isspace() | Returns True if all characters in the string are whitespaces |
istitle() | Returns True if the string follows the rules of a title |
isupper() | Returns True if all characters in the string are upper case |
join() | Converts the elements of an iterable into a string |
ljust() | Returns a left justified version of the string |
lower() | Converts a string into lower case |
lstrip() | Returns a left trim version of the string |
maketrans() | Returns a translation table to be used in translations |
partition() | Returns a tuple where the string is parted into three parts |
replace() | Returns a string where a specified value is replaced with a specified value |
rfind() | Searches the string for a specified value and returns the last position of where it was found |
rindex() | Searches the string for a specified value and returns the last position of where it was found |
rjust() | Returns a right justified version of the string |
rpartition() | Returns a tuple where the string is parted into three parts |
rsplit() | Splits the string at the specified separator, and returns a list |
rstrip() | Returns a right trim version of the string |
split() | Splits the string at the specified separator, and returns a list |
splitlines() | Splits the string at line breaks and returns a list |
startswith() | Returns true if the string starts with the specified value |
strip() | Returns a trimmed version of the string |
swapcase() | Swaps cases, lower case becomes upper case and vice versa |
title() | Converts the first character of each word to upper case |
translate() | Returns a translated string |
upper() | Converts a string into upper case |
zfill() | Fills the string with a specified number of 0 values at the beginning |
List Methods
Method | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
Dictionary Methods
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and value |
get() | Returns the value of the specified key |
items() | Returns a list containing a tuple for each key value pair |
keys() | Returns a list containing the dictionary's keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
Tuple Methods
Method | Description |
---|---|
count() | Returns the number of times a specified value occurs in a tuple |
index() | Searches the tuple for a specified value and returns the position of where it was found |
Set Methods
Method | Shortcut | Description |
---|---|---|
add() | Adds an element to the set | |
clear() | Removes all the elements from the set | |
copy() | Returns a copy of the set | |
difference() | - | Returns a set containing the difference between two or more sets |
difference_update() | -= | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item | |
intersection() | & | Returns a set, that is the intersection of two other sets |
intersection_update() | &= | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not | |
issubset() | <= | Returns whether another set contains this set or not |
issuperset() | >= | Returns whether this set contains another set or not |
pop() | Removes an element from the set | |
remove() | Removes the specified element | |
symmetric_difference() | ^ | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | ^= | Inserts the symmetric differences from this set and another |
union() | | | Return a set containing the union of sets |
update() | |= | Update the set with the union of this set and others |
File Methods
Method | Description |
---|---|
close() | Closes the file |
detach() | Returns the separated raw stream from the buffer |
fileno() | Returns a number that represents the stream, from the operating system's perspective |
flush() | Flushes the internal buffer |
isatty() | Returns whether the file stream is interactive or not |
read() | Returns the file content |
readable() | Returns whether the file stream can be read or not |
readline() | Returns one line from the file |
readlines() | Returns a list of lines from the file |
seek() | Change the file position |
seekable() | Returns whether the file allows us to change the file position |
tell() | Returns the current file position |
truncate() | Resizes the file to a specified size |
writable() | Returns whether the file can be written to or not |
write() | Writes the specified string to the file |
writelines() | Writes a list of strings to the file |
Common Operations
F-Strings
Syntax
Ein F-String wird mit einem vorangestellten f
oder F
gekennzeichnet und enthält Ausdrücke in geschweiften Klammern {}
, die zur Laufzeit ausgewertet werden.
<str> = f'{<el_1>}, {<el_2>}' # Curly brackets can also contain expressions.
<str> = '{}, {}'.format(<el_1>, <el_2>) # Or: '{0}, {a}'.format(<el_1>, a=<el_2>)
format_spec | fill | align | sign | width | grouping_option | "."precision | type |
---|---|
fill | any character |
align | "<" | ">" | "=" | "^" |
sign | "+" | "-" | " " |
width | digit+ |
grouping_option | "_" | "," |
precision | digit+ |
type | "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" |
Alignment
Option | Meaning |
---|---|
'<' | Forces the field to be left-aligned within the available space (this is the default for most objects). |
'>' | Forces the field to be right-aligned within the available space (this is the default for numbers). |
'=' | Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default for numbers when ‘0’ immediately precedes the field width. |
'^' | Forces the field to be centered within the available space. |
Integer Presentation Types
Type | Meaning |
---|---|
'b' | Binary format. Outputs the number in base 2. |
'c' | Character. Converts the integer to the corresponding unicode character before printing. |
'd' | Decimal Integer. Outputs the number in base 10. |
'o' | Octal format. Outputs the number in base 8. |
'x' | Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. |
'X' | Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well. |
'n' | Number. This is the same as 'd' , except that it uses the current locale setting to insert the appropriate number separator characters. |
None | The same as 'd' . |
Floating Point Presentation Types
Type | Meaning |
---|---|
'e' | Scientific notation. For a given precision p , formats the number in scientific notation with the letter ‘e’ separating the coefficient from the exponent. The coefficient has one digit before and p digits after the decimal point, for a total of p + 1 significant digits. With no precision given, uses a precision of 6 digits after the decimal point for float , and shows all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is used. |
'E' | Scientific notation. Same as 'e' except it uses an upper case ‘E’ as the separator character. |
'f' | Fixed-point notation. For a given precision p , formats the number as a decimal number with exactly p digits following the decimal point. With no precision given, uses a precision of 6 digits after the decimal point for float , and uses a precision large enough to show all coefficient digits for Decimal . If no digits follow the decimal point, the decimal point is also removed unless the # option is |
'F' | Fixed-point notation. Same as 'f' , but converts nan to NAN and inf to INF . |
'g' | General format. For a given precision p >= 1 , this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1 .The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp . Then, if m <= exp < p , where m is -4 for floats and -6 for Decimals , the number is formatted with presentation type 'f' and precision p-1-exp . Otherwise, the number is formatted with presentation type 'e' and precision p-1 . In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.With no precision given, uses a precision of 6 significant digits for float . For Decimal , the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise.Positive and negative infinity, positive and negative zero, and nans, are formatted as inf , -inf , 0 , -0 and nan respectively, regardless of the precision. |
'G' | General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too. |
'n' | Number. This is the same as 'g' , except that it uses the current locale setting to insert the appropriate number separator characters. |
'%' | Percentage. Multiplies the number by 100 and displays in fixed ('f' ) format, followed by a percent sign. |
None | For float this is the same as 'g' , except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.For Decimal , this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.The overall effect is to match the output of str() as altered by the other format modifiers. |
F-String Examples
>>> Person = collections.namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.name} is {person.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'
# General Options
{<el>:<10} # '<el> '
{<el>:^10} # ' <el> '
{<el>:>10} # ' <el>'
{<el>:.<10} # '<el>......'
{<el>:0} # '<el>'
# Strings
{'abcde':10} # 'abcde '
{'abcde':10.3} # 'abc '
{'abcde':.3} # 'abc'
{'abcde'!r:10} # "'abcde' "
# Numbers
{123456:10} # ' 123456'
{123456:10,} # ' 123,456'
{123456:10_} # ' 123_456'
{123456:+10} # ' +123456'
{123456:=+10} # '+ 123456'
{123456: } # ' 123456'
{-123456: } # '-123456'
# Floats
{1.23456:10.3} # ' 1.23'
{1.23456:10.3f} # ' 1.235'
{1.23456:10.3e} # ' 1.235e+00'
{1.23456:10.3%} # ' 123.456%'
More Examples
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
'January 27, 2017'
>>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
'today=January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
'0x400'
>>> foo = "bar"
>>> f"{ foo = }" # preserves whitespace
" foo = 'bar'"
>>> line = "The mill's closed"
>>> f"{line = }"
'line = "The mill\'s closed"'
>>> f"{line = :20}"
"line = The mill's closed "
>>> f"{line = !r:20}"
'line = "The mill\'s closed" '
Numeric Type
All numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence):
Operation | Result |
---|---|
x + y | sum of x and y |
x - y | difference of x and y |
x * y | product of x and y |
x / y | quotient of x and y |
x // y | floored quotient of x and y |
x % y | remainder of x / y |
-x | x negated |
+x | x unchanged |
abs(x) | absolute value or magnitude of x |
int(x) | x converted to integer |
float(x) | x converted to floating point |
complex(re, im) | a complex number with real part re, imaginary part im. im defaults to zero. |
c.conjugate() | conjugate of the complex number c |
divmod(x, y) | the pair (x // y, x % y) |
pow(x, y) | x to the power y |
x ** y | x to the power y |
Operation | Result |
---|---|
math.trunc(x) | x truncated to Integral |
round(x[, n]) | x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. |
math.floor(x) | the greatest Integral <= _x_ |
math.ceil(x) | the least Integral >= _x_ |
# Basic Functions
<num> = pow(<num>, <num>) # Or: <number> ** <number>
<num> = abs(<num>) # <float> = abs(<complex>)
<num> = round(<num> [, ±ndigits]) # `round(126, -1) == 130`
# Math
from math import e, pi, inf, nan, isinf, isnan # `<el> == nan` is always False.
from math import sin, cos, tan, asin, acos, atan # Also: degrees, radians.
from math import log, log10, log2 # Log can accept base as second arg.
# Statistics
from statistics import mean, median, variance # Also: stdev, quantiles, groupby.
# Random
from random import random, randint, choice # Also: shuffle, gauss, triangular, seed.
<float> = random() # A float inside [0, 1).
<int> = randint(from_inc, to_inc) # An int inside [from_inc, to_inc].
<el> = choice(<sequence>) # Keeps the sequence intact.
# Bin, Hex
<int> = ±0b<bin> # Or: ±0x<hex>
<int> = int('±<bin>', 2) # Or: int('±<hex>', 16)
<int> = int('±0b<bin>', 0) # Or: int('±0x<hex>', 0)
<str> = bin(<int>) # Returns '[-]0b<bin>'. Also hex().
Bitwise Operations
Operation | Result |
---|---|
x | y | bitwise or of x and y |
x ^ y | bitwise exclusive or of x and y |
x & y | bitwise and of x and y |
x << n | x shifted left by n bits |
x >> n | x shifted right by n bits |
~x | the bits of x inverted |
Sequence (list, tuple, range)
Operation | Result |
---|---|
x in s | True if an item of s is equal to x, else False |
x not in s | False if an item of s is equal to x, else True |
s + t | the concatenation of s and t |
s * n or n * s | equivalent to adding s to itself n times |
s[i] | _i_th item of s, origin 0 |
s[i:j] | slice of s from i to j |
s[i:j:k] | slice of s from i to j with step k |
len(s) | length of s |
min(s) | smallest item of s |
max(s) | largest item of s |
s.index(x[, i[, j]]) | index of the first occurrence of x in s (at or after index i and before index j) |
s.count(x) | total number of occurrences of x in s |
Mutable Sequence (list)
Operation | Result |
---|---|
s[i] = x | item i of s is replaced by x |
s[i:j] = t | slice of s from i to j is replaced by the contents of the iterable t |
del s[i:j] | same as s[i:j] = [] |
s[i:j:k] = t | the elements of s[i:j:k] are replaced by those of t |
del s[i:j:k] | removes the elements of s[i:j:k] from the list |
s.append(x) | appends x to the end of the sequence (same as s[len(s):len(s)] = [x] ) |
s.clear() | removes all items from s (same as del s[:] ) |
s.copy() | creates a shallow copy of s (same as s[:] ) |
s.extend(t) or s += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t ) |
s *= n | updates s with its contents repeated n times |
s.insert(i, x) | inserts x into s at the index given by i (same as s[i:i] = [x] ) |
s.pop() or s.pop(i) | retrieves the item at i and also removes it from s |
s.remove(x) | remove the first item from s where s[i] is equal to x |
s.reverse() | reverses the items of s in place |
Built-In Functions
Function | Description |
---|---|
abs() | Returns the absolute value of a number |
all() | Returns True if all items in an iterable object are true |
any() | Returns True if any item in an iterable object is true |
ascii() | Returns a readable version of an object. Replaces none-ascii characters with escape character |
bin() | Returns the binary version of a number |
bool() | Returns the boolean value of the specified object |
bytearray() | Returns an array of bytes |
bytes() | Returns a bytes object |
callable() | Returns True if the specified object is callable, otherwise False |
chr() | Returns a character from the specified Unicode code. |
classmethod() | Converts a method into a class method |
compile() | Returns the specified source as an object, ready to be executed |
complex() | Returns a complex number |
delattr() | Deletes the specified attribute (property or method) from the specified object |
dict() | Returns a dictionary (Array) |
dir() | Returns a list of the specified object's properties and methods |
divmod() | Returns the quotient and the remainder when argument1 is divided by argument2 |
enumerate() | Takes a collection (e.g. a tuple) and returns it as an enumerate object |
eval() | Evaluates and executes an expression |
exec() | Executes the specified code (or object) |
filter() | Use a filter function to exclude items in an iterable object |
float() | Returns a floating point number |
format() | Formats a specified value |
frozenset() | Returns a frozenset object |
getattr() | Returns the value of the specified attribute (property or method) |
globals() | Returns the current global symbol table as a dictionary |
hasattr() | Returns True if the specified object has the specified attribute (property/method) |
hash() | Returns the hash value of a specified object |
help() | Executes the built-in help system |
hex() | Converts a number into a hexadecimal value |
id() | Returns the id of an object |
input() | Allowing user input |
int() | Returns an integer number |
isinstance() | Returns True if a specified object is an instance of a specified object |
issubclass() | Returns True if a specified class is a subclass of a specified object |
iter() | Returns an iterator object |
len() | Returns the length of an object |
list() | Returns a list |
locals() | Returns an updated dictionary of the current local symbol table |
map() | Returns the specified iterator with the specified function applied to each item |
max() | Returns the largest item in an iterable |
memoryview() | Returns a memory view object |
min() | Returns the smallest item in an iterable |
next() | Returns the next item in an iterable |
object() | Returns a new object |
oct() | Converts a number into an octal |
open() | Opens a file and returns a file object |
ord() | Convert an integer representing the Unicode of the specified character |
pow() | Returns the value of x to the power of y |
print() | Prints to the standard output device |
property() | Gets, sets, deletes a property |
range() | Returns a sequence of numbers, starting from 0 and increments by 1 (by default) |
repr() | Returns a readable version of an object |
reversed() | Returns a reversed iterator |
round() | Rounds a numbers |
set() | Returns a new set object |
setattr() | Sets an attribute (property/method) of an object |
slice() | Returns a slice object |
sorted() | Returns a sorted list |
staticmethod() | Converts a method into a static method |
str() | Returns a string object |
sum() | Sums the items of an iterator |
super() | Returns an object that represents the parent class |
tuple() | Returns a tuple |
type() | Returns the type of an object |
vars() | Returns the dict property of an object |
zip() | Returns an iterator, from two or more iterators |
Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names, function names, or any other identifiers:
Keyword | Description |
---|---|
and | A logical operator |
as | To create an alias |
assert | For debugging |
break | To break out of a loop |
class | To define a class |
continue | To continue to the next iteration of a loop |
def | To define a function |
del | To delete an object |
elif | Used in conditional statements, same as else if |
else | Used in conditional statements |
except | Used with exceptions, what to do when an exception occurs |
False | Boolean value, result of comparison operations |
finally | Used with exceptions, a block of code that will be executed no matter if there is an exception or not |
for | To create a for loop |
from | To import specific parts of a module |
global | To declare a global variable |
if | To make a conditional statement |
import | To import a module |
in | To check if a value is present in a list, tuple, etc. |
is | To test if two variables are equal |
lambda | To create an anonymous function |
None | Represents a null value |
nonlocal | To declare a non-local variable |
not | A logical operator |
or | A logical operator |
pass | A null statement, a statement that will do nothing |
raise | To raise an exception |
return | To exit a function and return a value |
True | Boolean value, result of comparison operations |
try | To make a try...except statement |
while | To create a while loop |
with | Used to simplify exception handling |
yield | To return a list of values from a generator |
Exceptions
Exception | Description |
---|---|
ArithmeticError | Raised when an error occurs in numeric calculations |
AssertionError | Raised when an assert statement fails |
AttributeError | Raised when attribute reference or assignment fails |
Exception | Base class for all exceptions |
EOFError | Raised when the input() method hits an "end of file" condition (EOF) |
FloatingPointError | Raised when a floating point calculation fails |
GeneratorExit | Raised when a generator is closed (with the close() method) |
ImportError | Raised when an imported module does not exist |
IndentationError | Raised when indentation is not correct |
IndexError | Raised when an index of a sequence does not exist |
KeyError | Raised when a key does not exist in a dictionary |
KeyboardInterrupt | Raised when the user presses Ctrl+c, Ctrl+z or Delete |
LookupError | Raised when errors raised cant be found |
MemoryError | Raised when a program runs out of memory |
NameError | Raised when a variable does not exist |
NotImplementedError | Raised when an abstract method requires an inherited class to override the method |
OSError | Raised when a system related operation causes an error |
OverflowError | Raised when the result of a numeric calculation is too large |
ReferenceError | Raised when a weak reference object does not exist |
RuntimeError | Raised when an error occurs that do not belong to any specific exceptions |
StopIteration | Raised when the next() method of an iterator has no further values |
SyntaxError | Raised when a syntax error occurs |
TabError | Raised when indentation consists of tabs or spaces |
SystemError | Raised when a system error occurs |
SystemExit | Raised when the sys.exit() function is called |
TypeError | Raised when two different types are combined |
UnboundLocalError | Raised when a local variable is referenced before assignment |
UnicodeError | Raised when a unicode problem occurs |
UnicodeEncodeError | Raised when a unicode encoding problem occurs |
UnicodeDecodeError | Raised when a unicode decoding problem occurs |
UnicodeTranslateError | Raised when a unicode translation problem occurs |
ValueError | Raised when there is a wrong value in a specified data type |
ZeroDivisionError | Raised when the second operator in a division is zero |
Naming Conventions
PEP 8 - Style Guide for Python Code
Was | Wie | Beispiel |
---|---|---|
Module | snake_case | mein_modul.py |
Pakete | lowercase (ohne Underscores) | meinpaket |
Klassen | PascalCase | MeineKlasse |
Exception | PascalCase (enden mit Error) | DateiError |
Funktionen | snake_case | meine_funktion |
Methoden | snake_case | meine_methode |
Variablen | snake_case | mein_wert |
Konstanten | SCREAMING_SNAKE_CASE | MAX_WERT |
Private (geschützte) Namen | vorangestellter Unterstrich | _interne_Variable |
Magic Methods | zwei Unterstriche am Anfang und Ende | __init__ |
Name Mangling* | zwei Unterstriche am Anfang (class Attributes) | __foobar |
*zur Vermeidung von Namenskonflikten in Unterklassen
Code writing conventions
- Indentions: 4 spaces
- Line length: 80 characters
- Comments: 72 characters max
- Avoid inline comments.
- If inline comments are used keep them at the same vertical line.
- Documentation strings aka 'docstrings' should be written for every function, class, method or public module.
- Operators like < or += should have one empty space in front and behind (eg. 1 >= 2 and not 1>=2).
Glossary
Feature | Description |
---|---|
**kwargs | To deal with an unknown number of keyword arguments in a function, use the * symbol before the parameter name |
*args | To deal with an unknown number of arguments in a function, use the * symbol before the parameter name |
Access Arrays | How to access array items |
Access Dictionary Items | How to access items in a dictionary |
Access List Items | How to access items in a list |
Access Set Items | How to access items in a set |
Access Tuple Items | How to access items in a tuple |
Add Array Element | How to add elements from an array |
Add Class Methods | How to add a method to a class |
Add Class Properties | How to add a property to a class |
Add Dictionary Item | How to add an item to a dictionary |
Add List Items | How to add items to a list |
Add Set Items | How to add items to a set |
Arithmetic Operators | Arithmetic operator are used to perform common mathematical operations |
Array | Lists can be used as Arrays |
Array Length | How to get the length of an array |
Array Methods | Python has a set of Array/Lists methods |
Assign Values to Multiple Variables | How to assign values to multiple variables |
Assigning a String to a Variable | How to assign a string value to a variable |
Assignment Operators | Assignment operators are use to assign values to variables |
Bitwise Operators | Bitwise operators are used to compare (binary) numbers |
Boolean Values | True or False |
Built-In Data Types | Python has a set of built-in data types |
Built-in Modules | How to import built-in modules |
Call a Function | How to call a function in Python |
Change Dictionary Item | How to change the value of a dictionary item |
Change List Item | How to change the value of a list item |
Change Tuple Item | How to change the value of a tuple item |
Check if Dictionary Item Exists | How to check if a specified item is present in a dictionary |
Check if List Item Exists | How to check if a specified item is present in a list |
Check if Set Item Exists | How to check if a item exists |
Check if Tuple Item Exists | How to check if a specified item is present in a tuple |
Check In String | How to check if a string contains a specified phrase |
Class | A class is like an object constructor |
Class pass Statement | Use the pass statement in empty classes |
Comments | Comments are code lines that will not be executed |
Comparison Operators | Comparison operators are used to compare two values |
Complex | The complex number type |
Convert into JSON | How to convert a Python object in to JSON |
Copy a List | How to copy a list |
Copy Dictionary | How to copy a dictionary |
Create a Date Object | How to create a date object |
Create a Module | How to create a module |
Create an Iterator | How to create an iterator |
Create Child Class | How to create a child class |
Create Class | How to create a class |
Create Parent Class | How to create a parent class |
Create the init() Function | How to create the init() function |
Creating Variables | Variables are containers for storing data values |
Date Format Codes | The datetime module has a set of legal format codes |
Date Output | How to output a date |
Datetime Module | How to work with dates in Python |
Default Parameter Value | How to use a default parameter value |
Delete Object | How to delete an object |
Delete Object Properties | How to modify properties of an object |
Dictionary | A dictionary is an unordered, and changeable, collection |
Dictionary Length | How to determine the length of a dictionary |
Elif | elif is the same as "else if" in other programming languages |
Else | How to write an if...else statement |
Error Handling | How to handle errors in Python |
Escape Characters | How to use escape characters |
Evaluate Booleans | Evaluate a value or statement and return either True or False |
Float | The floating number type |
For | How to write a for loop |
For Break | How to break a for loop |
For Continue | How to stop the current iteration and continue wit the next |
For Else | How to use an else statement in a for loop |
For pass | Use the pass keyword inside empty for loops |
Format JSON | How to format JSON output with indentations and line breaks |
Format String | How to combine two strings |
Function | How to create a function in Python |
Function Arguments | How to use arguments in a function |
Function Recursion | Functions that can call itself is called recursive functions |
Function Return Value | How to return a value from a function |
Getting Data Type | How to get the data type of an object |
Global Keyword | The global keyword makes the variable global |
Global Scope | When does a variable belong to the global scope? |
Global Variables | Global variables are variables that belongs to the global scope |
Handle Many Exceptions | How to handle more than one exception |
Identity Operators | Identity operators are used to see if two objects are in fact the same object |
If AND | Use the and keyword to combine if statements |
If Indentation | If statements in Python relies on indentation (whitespace at the beginning of a line) |
If NOT | Use the not keyword to reverse the condition |
If OR | Use the or keyword to combine if statements |
If Statement | How to write an if statement |
Import From Module | How to import only parts from a module |
Indentation | Indentation refers to the spaces at the beginning of a code line |
Install PIP | How to install PIP |
Int | The integer number type |
Iterator vs Iterable | What is the difference between an iterator and an iterable |
Iterators | An iterator is an object that contains a countable number of values |
Join Two Lists | How to join two lists |
Join Two Sets | How to join two sets |
Join Two Tuples | How to join two tuples |
JSON | How to work with JSON in Python |
Keyword Arguments | How to use keyword arguments in a function |
Lambda Function | How to create anonymous functions in Python |
List Comprehension | How use a list comprehensive |
List Length | How to determine the length of a list |
Lists | A list is an ordered, and changeable, collection |
Logical Operators | Logical operators are used to combine conditional statements |
Loop Dictionary Items | How to loop through the items in a tuple |
Loop List Items | How to loop through the items in a tuple |
Loop Set Items | How to loop through the items in a set |
Loop Through a String | How to loop through a string |
Loop Through an Iterator | How to loop through the elements of an iterator |
Loop Through List Items | How to loop through the items in a list |
Looping Array Elements | How to loop through array elements |
Looping Through a range | How to loop through a range of values |
Membership Operators | Membership operators are used to test is a sequence is present in an object |
Metacharacters in RegEx | Metacharacters are characters with a special meaning |
Modify Object Properties | How to modify properties of an object |
Multiline Comments | How to insert comments on multiple lines |
Multiline Strings | How to create a multiline string |
Negative Indexing on a String | How to use negative indexing when accessing a string |
Nested Dictionaries | A dictionary within a dictionary |
Nested If | How to write an if statement inside an if statement |
Nested Loops | How to write a loop inside a loop |
Numbers | There are three numeric types in Python |
Object Methods | Methods in objects are functions that belongs to the object |
Operators | Use operator to perform operations in Python |
Output Variables | Use the print statement to output variables |
Parse JSON | How to parse JSON code in Python |
Passing a List as an Argument | How to pass a list as an argument |
PIP Packages | How to download and install a package with PIP |
PIP Remove Package | How to remove a package with PIP |
raise | How to raise an exception in Python |
Random Number | How to create a random number |
RegEx Functions | The re module has a set of functions |
RegEx Match Object | The Match Object is an object containing information about the search and the result |
RegEx Module | How to import the regex module |
RegEx Sets | A set is a set of characters inside a pair of square brackets with a special meaning |
RegEx Special Sequences | A backslash followed by a a character has a special meaning |
Remove Array Element | How to remove elements from an array |
Remove Dictionary Items | How to remove dictionary items |
Remove List Items | How to remove list items |
Remove Set Items | How to remove set items |
Remove Tuple Items | How to remove tuple items |
Renaming a Module | How to rename a module |
Return Boolean Value | Functions that return a Boolean value |
self | The self parameter refers to the current instance of the class |
Set | A set is an unordered, and unchangeable, collection |
Set Length | How to determine the length of a set |
Setting Data Type | How to set the data type of an object |
Shorthand If | How to write an if statement in one line |
Shorthand If Else | How to write an if...else statement in one line |
Slicing a String | How to slice a string |
Sort JSON | How to sort JSON |
Specify a Variable Type | How to specify a certain data type for a variable |
StopIteration | How to stop an iterator |
String Concatenation | How to combine strings |
String Length | How to get the length of a string |
String Literals | How to create string literals |
Strings are Arrays | Strings in Python are arrays of bytes representing Unicode characters |
super Function | The super() function make the child class inherit the parent class |
The Class init() Function | The init() function is executed when the class is initiated |
The pass Keyword in If | Use the pass keyword inside empty if statements |
The pass Statement in Functions | Use the pass statement in empty functions |
The strftime Method | How to format a date object into a readable string |
Try Else | How to use the else keyword in a try statement |
Try Finally | How to use the finally keyword in a try statement |
Tuple | A tuple is an ordered, and unchangeable, collection |
Tuple Length | How to determine the length of a tuple |
Tuple With One Item | How to create a tuple with only one item |
Type Conversion | How to convert from one number type to another |
Using the dir() Function | List all variable names and function names in a module |
Variable Names | How to name your variables |
Variables in Modules | How to use variables in a module |
What is an Array | Arrays are variables that can hold more than one value |
While | How to write a while loop |
While Break | How to break a while loop |
While Continue | How to stop the current iteration and continue wit the next |
While Else | How to use an else statement in a while loop |
Why Use Lambda Functions | Learn when to use a lambda function or not |