Python筆記③ 控制流
一,if語句
1,語句介紹
if是條件控制語句
if condition_fisrt:
statement_first
elif condition_second:
statement_second
else:
statement_third
簡單例子
a = 4 #定義變量a的值爲4
b = 5 #定義變量b的值爲5
if a>b: #如果a大於b
c = a #c等於a
else: #否則
c = b #c等於b
print(c) #很簡單理解如果怎樣,滿足條件的話就執行相應額度語句 #打印輸出c
輸出
5
2,簡化寫法
c = [a,b][a<b]
這裏第二個方括號爲條件判斷部分,第一個方括號爲輸出部分
True輸出b,False輸出a
getstr = input("請輸入性別:")
anstr = ['Gentlemen','Lady'][('female' or '女') == getstr.strip()]
print('Hi,',anstr,',welcome!')
輸出
請輸入性別:女
Hi, Gentlemen ,welcome!
二,while語句
1,語句介紹
while是循環執行語句,條件爲True則執行循環內容
while condition:
statement
簡單例子
c = 5
while c>0:
print(c)
c -= 1
輸出
5
4
3
2
1
2,十進制 to 二進制例子
a = input("Please enter a Decimal number:")
d = int(a)
s = " "
while d != 0:
d,f = divmod(d,2)
s = str(f) + s
print(s)
輸出
Please enter a Decimal number:4
100
三,for語句
1,語句介紹
for也是循環執行語句,它與while不同的地方是,它循環的是序列(sequence)容器
for item in sequence:
statement1
2, for中用切片
words = ['I','like','Python']
for item in words[:]:
words.insert(0,item)
print(item)
print(words)
輸出
I
like
Python
['Python', 'like', 'I', 'I', 'like', 'Python']
3,for中用range
for i in range(5):
print(i)
輸出
0
1
2
3
4
4,冒泡法排序
#bubble sort
n = [5,8,20,1]
print("原數據:",n)
for i in range(len(n) - 1):
for j in range(len(n) - i - 1):
if n[j] > n[j+1]:
n[j],n[j+1] = n[j+1],n[j]
print("Atfer bubble sort:",n)
輸出
原數據: [5, 8, 20, 1]
Atfer bubble sort: [1, 5, 8, 20]
5,for中用zip
x = [1,2,3,4,5,6]
y = (3,2,"hello")
for t1,t2 in zip(x,y):
print(t1,t2)
輸出
1 3
2 2
3 hello
6,for中用enumerate
x = ["hello",4,3.1453]
for i,item in enumerate(x):
print(i,' ',item)
輸出
0 hello
1 4
2 3.1453
四,break、continue、pass循環控制語句
1,語句簡介
- break:跳出當前的循環
- continue:終止這一次執行,進入下一次循環
- pass:什麼操作都不執行,用於結構上保持代碼完整
五,循環綜合例子
1,模擬人機語音交互控制流程
getstr = '' #定義一個空字符串,用來接收輸入
while("Bye"!=getstr): #使用while循環
if ''==getstr: #如果輸入字符爲空,輸出歡迎語句
print("hello! Password!")
getstr = input("請輸入字符,並按回車結束:") #調用input函數,獲得輸入字符串
if 'hello'==getstr.strip(): #如果輸入字符串爲hello,啓動對話服務
print('How are you today?')
getstr = "start" #將getstr設爲start,標誌是啓動對話服務
elif 'go away'==getstr.strip(): #如果輸入的是go away,則退出
print('sorry! bye-bye')
break #使用break語句退出循環
elif 'pardon'==getstr.strip(): #如果是pardon 重新再輸出一次
getstr = ''
continue #continue將結束本次執行,開始循環的下一次執行
else:
pass #什麼也不做,保持程序完整性
if 'start'== getstr: #如果getstr爲start,啓動對話服務
print('...init dialog-serving...') #僞代碼,打印一些語句,代表啓動了對話服務
print('... one thing...')
print('... two thing...')
print('......')
2,for實現列表推導式
Y = [1,1,1,0,1,1,0]
color = ['r' if item == 0 else 'b' for item in Y[:]]
print(color)
3,for打印“九九乘法表”
for x in range(1,10):
l = ['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]
for i in range(len(l)):
print(l[i],end=' ')
print('')
for x in range(1,10):
l = ['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]
print(' '.join(l[i] for i in range(len(l))))
print ('\n'.join([' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))
4,for循環的原理———迭代器
for語句的循環次數,由序列容器的數據個數決定
在循環過程中,隱式的使用了內置函數iter()
x = [1,2,3]
it = iter(x)
print(it.__next__())
print(it.__next__())
print(it.__next__())
#迭代完後再執行就會報錯
#print(it.__next__())
x = [1,2,3]
it = iter(x)
print(next(it))
print(next(it))
print(next(it))
#print(next(it))