Skip to content

Instantly share code, notes, and snippets.

@vpayno
Last active December 21, 2015 17:08
Show Gist options
  • Save vpayno/6338220 to your computer and use it in GitHub Desktop.
Save vpayno/6338220 to your computer and use it in GitHub Desktop.
Python Cheat Sheets - Numbers

Python Cheat Sheets

by Victor Payno

Numbers

Notes

  • Numbers are objects and have properties and callable methods. We have int, long (unlimited precision), complex, octal, hexadecimal and float types.

  • Longs don't need an L (or l) after the number since integers they are automatically converted to longs when they overflow.

n=123

n.bit_length()
n.conjugate()
n.denominator
n.numerator
n.real
n.imag

f=123.25
f.as_integer_ratio()
f.conjugate()
f.hex()
f.is_integer()
f.real
f.imag

c = complex(5,3)
c.real -> 5
c.imag -> 3

h = hex(10)
h -> '0xa'
h.upper() -> '0XA'
0x19.real -> 25
int('11', 16) -> 17
int('a', 16) -> 10

o = oct(8)
o -> '010'
print 010 -> 8
int('11', 8) -> 9   # int(string, base) -> base10

0b# -> binary number
0b101 == 5

bin(#) -> 0b#
oct(#) -> 0#
hex(#) -> 0x#

eval('10') -> 10
eval('010') -> 8
eval('0x10') -> 16

"%0, %x, %X" % (10, 10, 10) -> '12, a, A'

"%4.0f" % (1.1) -> '   1'
"%4.3f" % (1.1) -> '1.100'
"%.0f" % (1.1)  -> '1'

Arithmetic

b=1
b+=9
b -> 10

2**3 -> 8

3/2 -> 1
3//2 -> 1
3.0 / 2 -> 1.5
3.0 // 2 -> 1.0

8>>2 -> 2  # shift right

2<<2 -> 8  # shift left

pow(x, y) -> x**y
pow(x, y, z) -> (x**y) % z

abs(-1) -> 1

x|y -> bitwise or
x&y -> bitwise and
x^y -> bitwise exclusive or

~x -> commpliment

x or y
x and y
not x

import math

math.acos      math.cos       math.factorial math.ldexp     math.sin
math.acosh     math.cosh      math.floor     math.lgamma    math.sinh
math.asin      math.degrees   math.fmod      math.log       math.sqrt
math.asinh     math.e         math.frexp     math.log10     math.tan
math.atan      math.erf       math.fsum      math.log1p     math.tanh
math.atan2     math.erfc      math.gamma     math.modf      math.trunc
math.atanh     math.exp       math.hypot     math.pi
math.ceil      math.expm1     math.isinf     math.pow
math.copysign  math.fabs      math.isnan     math.radians

Bitwise operations

value << # steps to shift left (x 2)
value >> # steps to shift right (/ 2)

& -> and - returns value where both # have a 1
| -> or  - returns all the 1 bits
^ -> xor - returns either 1 bits but not both
~ -> 2's compliment (1's compliment + 1)

turn 4th bit on -> 0b0000 | 0b0100 => 0b0100
is 2nd bit in   -> 0b1111 & 0b0010 => 0b0010 (yes)
                   0b0000 & 0b0010 => 0b0000 (no)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment