1.條件語句
- if語句
- if-else語句
- if-elif-else語句
- assert關鍵詞
1.1 if語句
if expression:
expr_true_suite
- if 語句的 expr_true_suite 代碼塊隻有當條件表達式 expression 結果為真時才執行,否則将繼續執行緊跟在該代碼塊後面的語句。
- 單個 if 語句中的 expression 條件表達式可以通過布爾操作符 and,or和not 實作多重條件判斷。
例:
if 2 > 1 and not 2 >3:
print('U r right')
# U r right
1.2 if-else語句
if expression:
expr_true_suite
else:
expr_false_suite
Python 提供與 if 搭配使用的 else,如果 if 語句的條件表達式結果布爾值為假,那麼程式将執行 else 語句後的代碼。
例:
temp = input("猜猜小姐姐想的是哪個數字?")
guess = int(temp) # input 函數将接收的任何資料類型都預設為str
if guess == 666:
print("你也太了解小姐姐了!")
print("猜對也沒有獎勵")
else:
print("猜錯啦!")
print("遊戲結束!")
if語句支援嵌套,即在一個if語句中嵌入另一個if語句,進而構成不同層次的選擇結構。Python 使用縮進而不是大括号來标記代碼塊邊界,是以要特别注意else的懸挂問題。
例:
temp = input("不妨猜猜小哥哥想的是哪個數字:")
guess = int(temp)
if guess > 8
print("大了大了")
else:
if guess == 8:
print("猜對啦")
print("猜對也沒有獎勵哦")
else:
print("小了小了")
print("遊戲結束")
if-elif-else語句
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
elif 語句即為 else if,用來檢查多個表達式是否為真,并在為真時執行特定代碼塊中的代碼。
例:
temp = input('請輸入成績')
source = int(temp)
if 100 >= source >= 90:
print('A')
elif 90 >= source >= 80:
print('B')
elif 80 >= source >= 60:
print('C')
elif 60 > source >= 0:
print('D')
else:
print('輸入錯誤')
1.4 assert關鍵詞
assert這個關鍵詞我們稱之為“斷言”,當這個關鍵詞後邊的條件為 False 時,程式自動崩潰并抛出AssertionError的異常。
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
2.循環語句
- while循環
- while-else循環
- for循環
- for-else循環
- range()函數
- enumerate()函數
- break語句
- continue語句
- pass語句
- 推導式
- 綜合例子
2.1 while循環
while語句最基本的形式包括一個位于頂部的布爾表達式,一個或多個屬于while代碼塊的縮進語句。
while 布爾表達式:
代碼塊
while循環的代碼塊會一直循環執行,直到布爾表達式的值為布爾假。
如果布爾表達式不帶有<、>、==、!=、in、not in等運算符,僅僅給出數值之類的條件,也是可以的。當while後寫入一個非零整數時,視為真值,執行循環體;寫入0時,視為假值,不執行循環體。也可以寫入str、list或任何序列,長度非零則視為真值,執行循環體;否則視為假值,不執行循環體。
例:
count = 0
while count < 3:
temp = input('猜一個數字:')
guess = int(temp)
if guess > 8:
print('大了大了')
else:
if guess == 8
print('你真厲害')
print('猜對啦')
count = 3
else:
print('小了小了')
count = count + 1
print('遊戲結束')
布爾表達式傳回0,循環終止。例:
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
2.2 while-else循環
while 布爾表達式:
代碼塊
else:
代碼塊
當while循環正常執行完的情況下,執行else輸出,如果while循環中執行了跳出循環的語句,比如 break,将不執行else代碼塊的内容。
例:
count = 0
while count < 5:
print('%d is less than 5' % count)
count = count + 1
else:
print('%d is not less than 5' % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
count = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break
else:
print("%d is not less than 5" % count)
# 0 is less than 5
2.3 for循環
for循環是疊代循環,在Python中相當于一個通用的序列疊代器,可以周遊任何有序序列,如str、list、tuple等,也可以周遊任何可疊代對象,如dict。
for 疊代變量 in 可疊代對象:
代碼塊
每次循環,疊代變量被設定為可疊代對象的目前元素,提供給代碼塊使用。
例:
for i in 'ILoveLSGO':
print(i, end=' ') # 不換行輸出
# I L o v e L S G O
2.4 for-else循環
for 疊代變量 in 可疊代對象:
代碼塊
else:
代碼塊
當for循環正常執行完的情況下,執行else輸出,如果for循環中執行了跳出循環的語句,比如 break,将不執行else代碼塊的内容,與while - else語句一樣。
for num in range(10,20): # 疊代10到20之間的數字
for i in range(2,num): #根據因子疊代
if num % i == 0: #确定第一個因子
j = num / i #計算第二個因子
print('%d 等于 %d * %d % (num,i,j))
break #跳出目前循環
else:
print(num,'是一個質數')
# 10 等于 2 * 5
# 11 是一個質數
# 12 等于 2 * 6
# 13 是一個質數
# 14 等于 2 * 7
# 15 等于 3 * 5
# 16 等于 2 * 8
# 17 是一個質數
# 18 等于 2 * 9
# 19 是一個質數
2.5 range()函數
這個BIF(Built-in functions)有三個參數,其中用中括号括起來的兩個表示這兩個參數是可選的。
step=1 表示第三個參數的預設值是1。
range 這個BIF的作用是生成一個從start參數的值開始到stop參數的值結束的數字序列,該序列包含start的值但不包含stop的值。
例:
for i in range(2, 9): # 不包含9
print(i)
# 2
# 3
# 4
# 5
# 6
# 7
# 8
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
2.6 enumerate函數
sequence – 一個序列、疊代器或其他支援疊代對象。
start – 下标起始位置。
傳回 enumerate(枚舉) 對象
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1)) # 下标從 1 開始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
enumerate()與 for 循環的結合使用:
for i, a in enumerate(A)
do something with a
用 enumerate(A) 不僅傳回了 A 中的元素,還順便給該元素一個索引值 (預設從 0 開始)。此外,用 enumerate(A, j) 還可以确定索引起始值為 j。
例:
languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
print('I love', language)
print('Done!')
'''
I love Python
I love R
I love Matlab
I love C++
Done!
'''
for i, language in enumerate(languages, 2):
print(i, 'I love', language)
print('Done!')
'''
2 I love Python
3 I love R
4 I love Matlab
5 I love C++
Done!
'''
2.7 break語句
break語句可以跳出目前所在層的循環。
import random
secret = random.randint(1, 10) #[1,10]之間的随機數
while True:
temp = input("不妨猜一下小哥哥現在心裡想的是那個數字:")
guess = int(temp)
if guess > secret:
print("大了,大了")
else:
if guess == secret:
print("你這樣懂小哥哥的心思啊?")
print("哼,猜對也沒有獎勵!")
break
else:
print("小了,小了")
print("遊戲結束,不玩兒啦!")
2.8 continue語句
continue終止本輪循環并開始下一輪循環。
for i in range(10):
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
# 2
# 1
# 4
# 3
# 6
# 5
# 8
# 7
# 10
# 9
2.9 pass語句
pass 語句的意思是“不做任何事”,如果你在需要有語句的地方不寫任何語句,那麼解釋器會提示出錯,而 pass 語句就是用來解決這些問題的。
【例子】
def a_func():
# SyntaxError: unexpected EOF while parsing
【例子】
def a_func():
pass
pass是空語句,不做任何操作,隻起到占位的作用,其作用是為了保持程式結構的完整性。盡管pass語句不做任何操作,但如果暫時不确定要在一個位置放上什麼樣的代碼,可以先放置一個pass語句,讓代碼可以正常運作。
2.10 推導式
- 清單推導式
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]
x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
x = [(i, i ** 2) for i in range(6)]
print(x)
# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)
# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
print(a)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
- 元組推導式
a = (x for x in range(10))
print(a)
# <generator object <genexpr> at 0x0000025BE511CC48>
print(tuple(a))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
- 字典推導式
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
- 集合推導式
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
- 其他
d = 'i for i in "I Love Lsgogroup"'
print(d)
# i for i in "I Love Lsgogroup"
e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>
print(next(e)) # 0
print(next(e)) # 1
for each in e:
print(each, end=' ')
# 2 3 4 5 6 7 8 9
s = sum([i for i in range(101)])
print(s) # 5050
s = sum((i for i in range(101)))
print(s) # 5050
2.11 綜合例子
passwdList = ['123', '345', '890']
valid = False
count = 3
while count > 0:
password = input('enter password:')
for item in passwdList:
if password == item:
valid = True
break
if not valid:
print('invalid input')
count -= 1
continue
else:
break