python 表达式和语句及for、while循环练习实例
Python中表达式和语句及for、while循环练习
常用的表达式操作符: x+y,x-y x*y,x/y,x//y,x%y 逻辑运算: xory,xandy,notx 成员关系运算: xiny,xnotiny 对象实例测试: xisy,xnotisy 比较运算: xy,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 元组:(...) 序列:[...] 字典:{...} 三元选择表达式:xifyelsez 匿名函数:lambdaargs:expression 生成器函数发送协议:yieldx 运算优先级: (...),[...],{...} s[i],s[i:j] s.attribute s(...) +x,-x,~x x**y *,/,//,% +,- <<,>> & ^ | <,<=,>,>=,==,!= is,notis in,notin not and or lambda
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中的所有元素,类似如下 k1v1 k2v2 ... >>>d1={'x':1,'y':2,'z':3,'m':4} >>>for(k,v)ind1.items(): printk,v y2 x1 z3 m4 练习2:逐一显示列表中l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]中的索引为奇数的元素; >>>l1=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] >>>foriinrange(1,len(l1),2): printl1[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=[] >>>foriinl1: ifinotinl2: 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'] >>>foriinnamelist: ifiinremovelist: namelist.remove(i) >>>namelist ['stu1','stu2','stu4','stu5','stu6']
4)while循环练习
练习1:逐一显示指定列表中的所有元素; >>>l1=[1,2,3,4,5] >>>i=0 >>>whilei>>l1=[1,2,3,4,5] >>>whilel1: printl1.pop(0) 1 2 3 4 5 练习2:求100以内所有偶数之和; >>>i=0 >>>sum=0 >>>whilei<101: sum+=i i+=2 printsum 2550 >>>foriinrange(0,101,2): sum+=i printsum 2550 练习3:逐一显示指定字典的所有键;并于显示结束后说明总键数; >>>d1={'x':1,'y':23,'z':78} >>>i1=d1.keys() >>>whilei1: printi1.pop(0) else: printlen(d1) x y z 3 练习4:创建一个包含了100以内所有奇数的列表; >>>d1=[] >>>i=1 >>>whilei<101: d1.append(i) i+=2 >>>printd1 [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99] >>>d1=[] >>>foriinrange(1,101,2) d1.append(i) >>>printd1 [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99] 练习5:列表l1=[0,1,2,3,4,5,6],列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],以第一个列表中的元素为键,以第二个列表中的元素为值生成字典d1; >>>l1=[0,1,2,3,4,5,6] >>>l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] >>>d1={} >>>count=0 >>>iflen(l1)==len(l2): whilecount 以上这篇python表达式和语句及for、while循环练习实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。