python基礎知識2(表達式、判斷與循環)

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章