print(bin(4)) # 0b100
print(bin(5)) # 0b101
print(bin(~4), ~4) # -0b101 -5 按位取反
print(bin(4 & 5), 4 & 5) # 0b100 4 按位与,从低位对齐开始
print(bin(4 | 5), 4 | 5) # 0b101 5 按位或,从地位对齐开始
print(bin(4 ^ 5), 4 ^ 5) # 0b1 1 按位异或
print(bin(4 << 2), 4 << 2) # 0b10000 16 左移,最低位补0,移n位就是变为原来的2^n倍
print(bin(4 >> 2), 4 >> 2) # 0b100 1 右移,最低位丢弃
x, y = 4, 3
small = x if x < y else y
print(small)
`
small = 3
a = 1031
print(bin(a)) # 0b10000000111
print(a.bit_length()) # 11
teacher = "老马的程序人生"
print(teacher) # 老马的程序人生
a = 1031
print(a, type(a))
# 1031
import decimal
from decimal import Decimal
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)
#0.3333
print(True + True) # 2
print(True + False) # 1
print(True * False) # 0
print(bool(0), bool(0.00), bool(Flase) #False False False
print(bool(''), bool(()), bool([]), bool({
}), bool(set)
#False False False Flase
set1 = set([1, 1, 2, 2, 3]) #{1, 2, 3}
set2 = set([2, 2, 3, 4, 4]) #{2, 3, 4}
set3 = set1 & set2 #交集
print(set3) #{2, 3}
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
print(item, end='&')
print('hello world')
# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
print(item, 'another string', sep='&')
# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string
print(bin(4)) # 0b100
print(bin(5)) # 0b101
print(bin(~4), ~4) # -0b101 -5 按位取反
print(bin(4 & 5), 4 & 5) # 0b100 4 按位与,从低位对齐开始
print(bin(4 | 5), 4 | 5) # 0b101 5 按位或,从地位对齐开始
print(bin(4 ^ 5), 4 ^ 5) # 0b1 1 按位异或
print(bin(4 << 2), 4 << 2) # 0b10000 16 左移,最低位补0,移n位就是变为原来的2^n倍
print(bin(4 >> 2), 4 >> 2) # 0b100 1 右移,最低位丢弃
n << 1 -> 计算 n*2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n*(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
a = 2
b = 3
a = a ^ b
b = a ^ b #b=(a^b)^b=a^(b^b)=a^0=a
a = a ^ b #a=(a^b)^b=(a^b)^a=b 以为第一个b还是原来的b,第二个b=a
print(a) #3
00 00 01 01 -> 5
&
11 11 10 11 -> -5
---
00 00 00 01 -> 1
00 00 11 10 -> 14
&
11 11 00 10 -> -14
---
00 00 00 10 -> 2
a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
a = set([1, 3, 5, 7])
b = set([1, 3, 7, 8])
print(a & b) 交 {
1, 3, 7}
print(a | b) 并 {
1, 3, 5, 7, 8}
print(bin(3)) # 0b11
print(bin(-3)) # -0b11
print(bin(-3 & 0xffffffff))
# 0b11111111111111111111111111111101
print(bin(0xfffffffd))
# 0b11111111111111111111111111111101
print(0xfffffffd) # 4294967293