Python中表达式和语句及for、while循环练习
1)表达式
常用的表达式操作符:x + y, x - yx * y, x / y, x // y, x % y逻辑运算:x or y, x and y, not x成员关系运算:x in y, x not in y对象实例测试:x is y, x not is y比较运算:x < y, x > y, x <= y, x >= y, x == y, x != y位运算:x | y, x & y, x ^ y, x << y, x >> y一元运算:-x, +x, ~x:幂运算:x ** y索引和分片:x[i], x[i:j], x[i:j:stride]调用:x(...)取属性: x.attribute元组:(...)序列:[...]字典:{...}三元选择表达式:x if y else z匿名函数:lambda args: expression生成器函数发送协议:yield x 运算优先级:(...), [...], {...}s[i], s[i:j]s.attributes(...)+x, -x, ~xx ** y*, /, //, %+, -<<, >> &^|<, <=, >, >=, ==, !=is, not isin, not innotandorlambda
2)语句:
赋值语句 调用 print: 打印对象 if/elif/else: 条件判断 for/else: 序列迭代 while/else: 普通循环 pass: 占位符 break: continue def return yield global: 命名空间 raise: 触发异常 import: from: 模块属性访问 class: 类 try/except/finally: 捕捉异常 del: 删除引用 assert: 调试检查 with/as: 环境管理器 赋值语句: 隐式赋值:import, from, def, class, for, 函数参数 元组和列表分解赋值:当赋值符号(=)的左侧为元组或列表时,Python会按照位置把右边的对象和左边的目标自左而右逐一进行配对儿;个数不同时会触发异常,此时可以切片的方式进行; 多重目标赋值 增强赋值: +=, -=, *=, /=, //=, %=,
3)for循环练习
练习1:逐一分开显示指定字典d1中的所有元素,类似如下k1 v1k2 v2... >>> d1 = { 'x':1,'y':2,'z':3,'m':4 } >>> for (k,v) in d1.items(): print k,v y 2 x 1 z 3 m 4 练习2:逐一显示列表中l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]中的索引为奇数的元素; >>> l1 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] >>> for i in range(1,len(l1),2): print l1[i] Mon Wed Fri 练习3:将属于列表l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],但不属于列表l2=["Sun","Mon","Tue","Thu","Sat"]的所有元素定义为一个新列表l3; >>> l1 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] >>> l2 = ["Sun","Mon","Tue","Thu","Sat"] >>> l3 = [ ] >>> for i in l1: if i not in l2:l3.append(i) >>> l3 ['Wed', 'Fri'] 练习4:已知列表namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'],删除列表removelist=['stu3', 'stu7', 'stu9'];请将属于removelist列表中的每个元素从namelist中移除(属于removelist,但不属于namelist的忽略即可); >>> namelist= ['stu1','stu2','stu3','stu4','stu5','stu6','stu7'] >>> removelist = ['stu3', 'stu7', 'stu9'] >>> for i in namelist: if i in removelist :namelist.remove(i) >>> namelist ['stu1', 'stu2', 'stu4', 'stu5', 'stu6']
新闻热点
疑难解答