type() returns the type of a variable.
isinstance(var, type) check whether
var is of
Python variables cannot be declared without assigning a value to it.
Boolean values can be treated to numbers.
True is 1,
False is 0.
To test for identity, use
is keyword. E.g.
var1 is var2 == False. Identity means the two names refer to the same object.
True if any element of the iterable is true.
True if all elements of the iterable is true.
int: can be arbitrarily large.
float: is accurate to 15 decimal places.
int()method truncates towards 0.
round(value, ndigits)round towards nearest even digit (1.5 and 2.5 both round to 2), and
ndigitscan be negative (round to 10, 100, etc.).
fractions.Fraction(numerator, denominator). By
import fractions, we can use the built-in fraction class. Note denominator cannot be 0.
mathpackage. It contains constants
math.pi, all trigonometric functions.
- 0 and 0.0 are
False, everything else is
True. Be careful about rounding error in floating points!!!
2 + 5jgenerates complex number. All the usual number operations are supported, and use
cmathmodule (instead of
math) if necessary.
float('nan')creates infinity, negative infinity and NaN. To check whether a value is inf or nan, use
iscannot be used to check for nan!
/: floating point division, returns float no matter what.
//: integer division. It always truncates down (towards negative infinity), so
11//2 == 5,
-11//2 == -6.
11 ** 2 == 121.
Floating point can’t accurately represent all base-10 decimals. If needed (especially in finance world), use
format(value, definition) function.
definition is a string like
width is the width of the output, 0 means no override.
< is left-justified,
> is right-justitied, and
^ is centered.
digits is the number of digits in accuracy.
E means exponential notation. Place a
. inserts thousands separator.
hex(x) converts integer
x into its binary, octal, and hexadecimal representation.
format(x, 'b|o|x') does the same thing, except it won’t produce
Integer is signed, so negative value has a negative sign prefixing it. To convert to the unsigned representation, add the maximum number to it to set the bit length.
To convert back to decimal, use
None is Python’s
None to anything other than
None is always
None itself is evaluated to
An immutable sequence of numbers between 0 and 255. To mutate a byte in
bytes object, convert it to
bytearray object. Indexing on it returns integers, not individual characters.
To create with literals, use
b'someString'. To use constructors, use
String and bytes are different datatypes, so they cannot be concatenated with each other.
Bytes can be converted to strings using
by.decode(encoding) method. Similarly,
s.encode(encoding) converts a UTF-8 string into bytes.
Bytes supports most of the same built-in operations as text string, but not string formatting. Some of them also works with
bytearray too. To use regular expression, pattern needs to be declared as byte string too.