1.statement声明
a='fff'
b=1 #statement通常为赋值语句
2.expression表达式(通常有返回结果)
#值,变量和运算符共同组成的整体我们将其称为表达式。其形式有表达式,变量表达式,计算表达式,字符串表达式。
exec执行声明语句,eval执行表达式
exec('a=5')
b=3
eval('a+b+5')
3.判断逻辑
表达式、判断与循环
if
age=88
if age<18:
print('青年')
if else
if age<18:
print('青年')
else:
print('成年')
if elif
if age<18:
print('青年')
elif age>18 and age<60:
print('成年')
elif age>60:
print('老年')
三元表达式
'a' if age>50 else 'b'
#等价于
if age>50:
print('a')
else:
print('b')
4.循环结构
for(一般用于遍历)
str='study'
for item in str:
print(item)
print("") #换行
-->
s
t
u
d
y
while(一般用于筛选)
count=1
while(count<5):
print (count)
count+=1
print("")
-->
1
2
3
4
break ,continue
i=0
while True:
i+=1
if i==3:
contine #结束某一次循环
if i>5:
break #结束整个循环
print(i)
-->
1
2
4
5
5.扩展:列表推导式,可迭代对象与迭代器,生成器
a=[1,2,3,4,5,6,7,8,9]
b=[]
for item in a:
b.append(item**2)
print(b)
#等同于下式
b=[item**2 for item in a ]
-->
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
#列表推导式:从一个列表中生成一个新的列表,简化了循环的算法
l1=[x+1 for x in range(30) if x%3==0] #新的列表中元素,来源于0-29这个list中,所有整除3的元素加1
-->[1, 4, 7, 10, 13, 16, 19, 22, 25, 28]
#可迭代对象工Iterable:可以披for循环的对象统称为可迭代对象Iterable,list,str,diet这些是可迭代
#迭代器Iterator:可被next调用的迭代器。
#next(l1) #TypeErrort: 'list' object is not an iterator
#用iter将一来个可迭代对象变为迭代器
l1=iter(l1)
next(l1),next(l1)
--> 1 4
#生成器Generator:是一个迭代器 然后其内容是按需生成
#列表是一次性生成,缺点是当内容过大时会占用大量内容,那能不能用到多少生成多少呢?
#Python里一边循环一边计算 (惰性计算)的迭代器 称为生成器 (Generator)
1.直接从列表表达式生成
g1=(x**2 for x in range (30) if x%2==0)
type(g1)
--> <class 'generator'>
next(g1),next(g1),next(g1),next(g1) #python3 没有next(),_next_()函数
-->0 4 16 36
2.函致生成,与yield关键字
def g2_func(n):
for i in range(n):
yield i**2
g2= g2_func(7)
next (g2),next(g2)
#yield from/子迭代器,后面直接是可迭代对象.
def yield_from__iter (iter_object):
yield from iter_object
y1=yield_from__iter('China')
next(y1)
--> C