第五章 循環(huán)與判斷
5.1 邏輯控制與循環(huán)
邏輯判斷一一True & False
布爾類型(Boolean)的數(shù)據(jù)只有兩種,True 和 False (需要注意的是首字母大寫)辉阶。人類以真?zhèn)蝸砼袛嗍聦崳谟嬎銠C世界中真?zhèn)螌膭t是1和0谆甜。
1 > 2 # False
1 < 2 <3 # True
42 != '42' # True
'Name' == 'name' # False
'M' in 'Magic' # True
number = 12
number is 12 # True
- 這里“==”是等于,一個等號是賦值规辱,不等于用“谆棺!=”這個表示
- 字符串和數(shù)字不能比較
- 字符串比較區(qū)分大小寫
- True是1,F(xiàn)alse是0按摘,所以True>False
成員運算符與身份運算符
- in, not in a in b, a是否在b的里面(歸屬關系)
- 列表 album = [],像這樣就是創(chuàng)建了一個列表,append()可以添加元素到集合的最后
字符串包券、浮點纫谅、整數(shù)、布爾類型溅固、變量甚至是另一個列表都可以儲存在列表中
album = []
album = ['Black Star', 'David Bowie', 25, True]
album.append('new song')
print(album[0], album[-1])
print('Black Star' in album)
- is, is not a is b, a是b嗎(身份鑒別)
the_Eddie = 'Eddie'
name = 'Eddie'
the_Eddie == name #True
the_Eddie is name #True
在 Python 中任何對象都可判斷其布爾值付秕,除了 0、None 和所有空的序列與集合(列表侍郭,字典询吴,集合)布爾值為 False 之外,其它的都為 True
bool(0) #False
bool([]) #False
bool('') #False
bool(False) #False
bool(None) #False
布爾運算符
and亮元、or 用于布爾值的之間的運算
1 < 3 and 2 < 5 #True
1 < 3 and 2 > 5 #False
1 < 3 or 2 > 5 #True
1 > 3 or 2 > 5 #False
5.2 條件控制
if...else
if 條件為True時冒號猛计,做……,條件為False時爆捞,做……
- 例子奉瘤,做個登錄的函數(shù),輸入密碼為12345時顯示密碼正確煮甥,除此以外顯示密碼錯誤并提示重新輸入密碼
def account_login():
password = input('Password:') # input輸入的是字符串
if password == '12345': # 輸入的密碼等于12345
print('Login success!')
else:
print('Wrong password or invalid input!')
account_login() # 重新輸入密碼
account_login()
elif
多條件判斷同樣很簡單盗温,只需在 if 和else 之間增加上 elif,用法和 if 是一致的成肘。而且條件的判斷也是依次進行的卖局,首先看條件是否成立,如果成立那么就運行下面的代碼双霍,如果不成立就接著順次地看下面的條件是否成立砚偶,如果都不成立則運行 else 對應的語句。
上面的例子加個重置密碼的功能
password_list = ['*#*#', '12345']
def account_login():
password = input('Password:')
password_correct = password == password_list[-1]
password_reset = password == password_list[0]
if password_correct:
print('Login success!')
elif password_reset:
new_password = input('Enter a new password')
password_list.append(new_password)
print('Your password has changed successfully!')
account_login()
else:
print('Wrong password or invalid input!')
account_login()
account_login()
5.3 循環(huán)
for 循環(huán)
for every_letter in 'Hello world':
print(every_letter)
把 for 循環(huán)所做的事情概括成一句話就是:于...其中的每一個元素洒闸,做...事情染坯。
-
例子1 試著用for循環(huán)打印
1 + 1 = 2
2 + 1 = 3
.
.
10 + 1 = 11
(這里會用到一個range(a,b)括號中填上數(shù)字,就可以得到一個具有連續(xù)整數(shù)的序列)
for num in range(1, 11):
print(str(num) + ' + 1' + ' = ' + str(num + 1))
print('{} + 1 = {}'.format(num, num+1)) #也可以這樣寫
- 例子2 把 for 和 if 結合起來使用顷蟀。實現(xiàn)這樣一個程序:歌曲列表中有三首歌“Holy Diver, Thunderstruck, Rebel Rebel”酒请,當播放到每首時骡技,分別顯示對應的歌手名字“Dio, AC/DC, David Bowie”鸣个。
song_list = ['Holy Diver', 'Thunderstruck', 'Rebel Rebel']
for song in song_list:
if song == 'Holy Diver':
print(song, ' - Dio')
elif song == 'Thunderstruck':
print(song, ' - AC/DC')
elif song == 'Rebel Rebel':
print(song, ' - David Bowie')
!2茧囤萤!這里的print(song, ' - David Bowie')中的逗號解釋
'+'號是進行拼接,參與'+'的參數(shù)類型必須是同類型的數(shù)據(jù)
',' 號是將變量分隔開是趴,可以是不同類型的數(shù)據(jù)
比如:
print 'abc'+'123' # result: abc123
print 'abc', '123' # result: abc 123
嵌套循環(huán)
- 打印個乘法口訣表
for i in range(1, 10):
for j in range(1, 10):
print('{} × {} = {}'.format(i, j, i * j))
變量 i 每取一次值涛舍,內(nèi)層循環(huán)就要依次將 1~9 中存儲在變量 j 中
While 循環(huán)
只要…條件成立,就一直做…唆途。
while 1 < 3:
print('1 is smaller than 3')
這個循環(huán)會一直循環(huán)下去富雅,要及時停止,像這種循環(huán)我們叫死循環(huán)
- 如何控制while循環(huán)毕贼,其中一種方式就是:在循環(huán)過程中制造某種可以使循環(huán)停下來的條件
count = 0
while True:
print('Repeat this line !')
count = count + 1
if count > 5:
break
- 如何控制while循環(huán)鬼癣,另外一種方法是:改變使循環(huán)成立的條件
count = 0
while count < 5:
print('Repeat this line !')
count = count + 1
- 在登錄函數(shù)基礎上啤贩,改成輸入密碼錯誤3次就不許再輸入了
def account_login():
tries = 3
while tries > 0:
password = input('Password:')
password_correct = password == password_list[-1]
password_reset = password == password_list[0]
if password_correct:
print('Login success!')
break
elif password_reset:
new_password = input('New Password:')
password_list.append(new_password)
print('Your password has changed successfully')
account_login()
break
else:
print('Wrong password or invalid input!')
tries = tries - 1
print(tries, 'times left')
else:
print('Your account has been suspended')
account_login()
這里用了個while…else痹屹,
意思是當 while/for 循環(huán)正常執(zhí)行完的情況下志衍,執(zhí)行 else 輸出;
如果當 while/for 循環(huán)中執(zhí)行了跳出循環(huán)的語句雄驹,比如 break淹辞,將不執(zhí)行 else 代碼塊的內(nèi)容