"""蓝色天空网 mbsky.com: each operator branch and real short-circuit observations."""
from pathlib import Path
import sys,operator,asyncio,__future__,ast
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
c=Checks()
class Matrix2:
def __init__(self,rows):self.rows=[list(r)for r in rows]
def __matmul__(self,other):
if not isinstance(other,Matrix2):return NotImplemented
return Matrix2([[sum(self.rows[i][k]*other.rows[k][j]for k in range(2))for j in range(2)]for i in range(2)])
async def awaited_power():
async def base():return 2
return await base() ** 3
def main():
arithmetic=[('add',operator.add,11),('subtract',operator.sub,5),('multiply',operator.mul,24),('divide',operator.truediv,8/3),('remainder',operator.mod,2),('floor',operator.floordiv,2)]
for name,function,want in arithmetic:c.eq('arithmetic '+name,function(8,3),want)
c.eq('power',2**3,8);c.eq('negative floor and remainder',(-8//3,-8%3),(-3,1));c.eq('float floor is float',type(8.0//3).__name__,'float')
c.raises('divide zero',ZeroDivisionError,lambda:8/0);c.raises('remainder zero',ZeroDivisionError,lambda:8%0)
for name,function,want in [('eq',operator.eq,False),('ne',operator.ne,True),('gt',operator.gt,True),('lt',operator.lt,False),('ge',operator.ge,True),('le',operator.le,False)]:
value=function(8,3);c.eq('comparison '+name,value,want);c.eq('comparison result bool '+name,type(value).__name__,'bool')
c.eq('NaN not self-equal',(lambda n:n==n)(float('nan')),False);c.raises('complex unordered',TypeError,lambda:(1+2j)>2)
value=8;states=[value];value+=3;states.append(value);value-=2;states.append(value);value*=2;states.append(value);value/=3;states.append(value);c.eq('assignment first transitions',states,[8,11,9,18,6.0])
value=8;value%=3;c.eq('%=',value,2);value**=3;c.eq('**=',value,8);value//=3;c.eq('//=',value,2)
items=[1];alias=items;items+=[2];c.eq('list += mutates alias',alias,[1,2]);c.eq('list += keeps identity',items is alias,True)
separate=[1];old=separate;separate=separate+[2];c.eq('list + rebinding leaves old',old,[1]);c.eq('list + new identity',separate is old,False)
calls=[]
def target():calls.append('target');return holder
holder=[[1]];target()[0]+=[2];c.eq('augmented target evaluated once',calls,['target']);c.eq('augmented item result',holder,[[1,2]])
lengths=[]
def get_length():lengths.append(1);return 4
if (size:=get_length())>3:chosen='long'
c.eq('walrus actual length',size,4);c.eq('walrus call once',lengths,[1]);c.eq('walrus condition result',chosen,'long')
if wrong:=get_length()>3:pass
c.eq('unparenthesized walrus binds comparison',wrong,True);c.eq('walrus not int here',type(wrong).__name__,'bool')
c.eq('bits each',(60&13,60|13,60^13,~60,60<<2,60>>2),(12,61,49,-61,240,15));c.eq('8bit explicit mask',(~60)&0xff,195);c.eq('left retains high bits',255<<1,510);c.eq('negative arithmetic right',-9>>1,-5);c.raises('negative shift',ValueError,lambda:1<<-1)
actions=[]
def observe(label,value):actions.append(label);return value
result=observe('x',True)or observe('y',False)and observe('z',False)
c.eq('precedence result',result,True);c.eq('or prevents y and z evaluation',actions,['x'])
actions.clear();result=(observe('x',True)or observe('y',False))and observe('z',False);c.eq('parentheses result',result,False);c.eq('parentheses evaluated branches',actions,['x','z'])
c.eq('and false operand returned',[]and 9,[]);c.eq('or truthy operand returned','sky'or 9,'sky');c.eq('not bool',not [],True)
c.eq('substring member','sky'in'mbsky.com',True);c.eq('sequence not member',9 not in [1,2],True);c.eq('dict tests key',('sky'in{'sky':1},1 in{'sky':1}),(True,False));c.eq('set member',2 in{1,2},True)
a=[1,2];b=a;copy=a[:];c.eq('identity alias',a is b,True);c.eq('separate equal',(a==copy,a is copy,a is not copy),(True,False,True));c.eq('id for same living object',id(a)==id(b),True)
c.eq('power right associates',2**3**2,512);c.eq('unary vs power',(-2**2,(-2)**2,2**-2),(-4,4,0.25));c.eq('subtraction left groups',8-3-1,4)
comparisons=[]
def middle():comparisons.append('middle');return 2
c.eq('chained comparison',1<middle()<3,True);c.eq('chain computes middle once',comparisons,['middle'])
c.eq('conditional right groups',1 if False else 2 if True else 3,2);c.eq('await binds before power',asyncio.run(awaited_power()),8)
product=Matrix2([[1,2],[3,4]])@Matrix2([[2,0],[1,2]]);c.eq('actual matrix protocol',product.rows,[[4,4],[10,8]]);c.raises('matrix nonmatching type',TypeError,lambda:Matrix2([[1,0],[0,1]])@3)
c.raises('old diamond normal syntax rejected',SyntaxError,lambda:compile('7 <> 9','<owned-legacy>','eval'))
legacy=compile('7 <> 9','<owned-historical-flag>','eval',flags=__future__.barry_as_FLUFL.compiler_flag,dont_inherit=True);c.eq('isolated historical compiler flag',eval(legacy,{'__builtins__':{}}),True)
c.eq('normal inequality remains',7!=9,True)
if not True or False:branch=1
elif not True or not False and False:branch=2
elif not True or False or not False and True:branch=3
else:branch=4
quiz=[
dict(goal='exponent',question='2的5次方应写成?',options=['2^5','2**5','2^^5'],answer=1,actual=2**5),
dict(goal='remainder',question='29 % 4 的结果?',options=['1','7','0'],answer=0,actual=29%4),
dict(goal='power-precedence',question='4 * 2 ** 3 等于?',options=['512','32','24'],answer=1,actual=4*2**3),
dict(goal='floor',question='-9 // 2 等于?',options=['-4','4','-5'],answer=2,actual=-9//2),
dict(goal='associativity',question='2 ** 3 ** 2 按哪种方式分组?',options=['(2**3)**2','2**(3**2)','随机'],answer=1,actual=2**3**2),
dict(goal='short-circuit',question='True or False and False 的结果?',options=['True','False','语法错误'],answer=0,actual=True or False and False),
dict(goal='not-and-or',question='按本章not/and/or条件分支实例,进入第几分支?',options=['1','2','3','4'],answer=2,actual=branch)]
for q,want in zip(quiz,[32,1,32,-5,512,True,3]):c.eq('quiz '+q['goal'],q['actual'],want)
c.finish('python3-basic-operators',quiz=quiz,operator_scope='each named branch only; no full source-example acceptance')
if __name__=='__main__':main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-basic-operators.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-basic-operators.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip