Python学习6——条件,循环语句
條件語(yǔ)句
真值也稱布爾值。
用作布爾表達(dá)式時(shí),下面的值都將被視為假:False None? 0? ?""? ?()? ?[]? ?{}。
布爾值True和False屬于類型bool,而bool與list、str和tuple一樣,可用來(lái)轉(zhuǎn)換其他的值。
>>> bool('I think,therefore I am') True >>> bool(10) True >>> bool('') False >>> bool(0) False?
if語(yǔ)句
>>> name = input('What is your name?') What is your name?Gumby >>> if name.endswith('Gumby'):print(name)Gumby如果條件(if和冒號(hào)之間的表達(dá)式)是前面定義的真,就執(zhí)行后續(xù)代碼塊,如果條件為假,就不執(zhí)行。
?
else子句,elif子句,嵌套代碼塊
>>> name = input('What is your name?') What is your name?Gumby >>> if name.endswith('Gumby'):if name.startswith('Mr.'):print('Hello,Mr.Gumby')elif name.startswith('Mrs.'):print('Hello,Mrs.Gumby')else:print('Hello,Gumby') else:print('Hello,stranger')Hello,Gumby?
比較運(yùn)算符:
| 表達(dá)式 | 描述 |
| x == y | x等于y |
| x < y | x小于y |
| x > y | x大于y |
| x >= y? | x大于或等于y |
| x <= y | x小于或等于y |
| x != y | x不等于y |
| x is y | x和y是同一個(gè)對(duì)象 |
| x is not y | x和y是不同的對(duì)象 |
| x in y | x是容器y的成員 |
| x not in y | x不是容器y的成員 |
?
?
?
?
?
?
?
?
?
>>> x = y = [1,2,3] >>> z = [1,2,3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False >>> #is檢查兩個(gè)對(duì)象是否相同(不是相等),變量x和y指向同一個(gè)列表,而z指向另一個(gè)列表(即使它們包含的值是一樣的),這兩個(gè)列表雖然相等,但并非同一個(gè)列表。?
ord函數(shù)可以獲取字母的順序值,chr函數(shù)的作用與其相反:
>>> ord('a') 97 >>> ord('v') 118 >>> chr(118) 'v'?
斷言:assert
>>> age = 10 >>> assert 0 < age < 11 >>> age = -1 >>> assert 0 < age < 11 Traceback (most recent call last):File "<pyshell#47>", line 1, in <module>assert 0 < age < 11 AssertionError >>> age = -1 >>> assert 0 < age < 11,'the age must be realistic' #字符串對(duì)斷言做出說(shuō)明 Traceback (most recent call last):File "<pyshell#49>", line 1, in <module>assert 0 < age < 11,'the age must be realistic' #字符串對(duì)斷言做出說(shuō)明 AssertionError: the age must be realistic?
循環(huán)
while 循環(huán)
>>> name = '' >>> while not name.strip(): #屏蔽空格name = input('please enter your name:')print('hello,{}!'.format(name))please enter your name:Momo hello,Momo!?
for循環(huán)
>>> numbers = [0,1,2,3,4,5,6,7,8] >>> for number in numbers:print(number)0 1 2 3 4 5 6 7 8內(nèi)置函數(shù)range():
>>> range(0,10) range(0, 10) >>> list(range(0,10)) #范圍[0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(10) #如果只提供1個(gè)位置,將把這個(gè)位置視為結(jié)束位置,并假定起始位置為0 range(0, 10) >>> for num in range(1,10):print(num)1 2 3 4 5 6 7 8 9?
迭代字典:
>>> d = dict(a=1,b=2,c=3) >>> d {'a': 1, 'b': 2, 'c': 3} >>> for key in d:print(key,'to',d[key])a to 1 b to 2 c to 3換一種方式迭代:
>>> for key,value in d.items():print(key,'to',value)a to 1 b to 2 c to 3 >>> d.items() dict_items([('a', 1), ('b', 2), ('c', 3)])?
并行迭代:
同時(shí)迭代2個(gè)序列。
>>> names = ['aaa','bbb','ccc'] >>> ages = [10,11,12] >>> for i in range(len(names)):print(names[i],'is',ages[i],'years old')aaa is 10 years old bbb is 11 years old ccc is 12 years old內(nèi)置函數(shù)zip,可以將2個(gè)序列縫合起來(lái),并返回一個(gè)由元組組成的序列。
>>> list(zip(names,ages)) [('aaa', 10), ('bbb', 11), ('ccc', 12)] >>> for name,age in zip(names,ages):print(name,'is',age,'years old')aaa is 10 years old bbb is 11 years old ccc is 12 years oldzip函數(shù)可以縫合任意數(shù)量的序列,當(dāng)序列的長(zhǎng)度不同時(shí),zip函數(shù)將在最短的序列用完后停止縫合。
>>> list(zip(range(5),range(10))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]?
迭代時(shí)獲取索引:
>>> strings = ['aac','ddd','aa','ccc'] >>> for string in strings:if 'aa' in string: #替換列表中所有包含子串‘a(chǎn)a’的字符串index = strings.index(string) #在列表中查找字符串strings[index] = '[censored]'>>> strings ['[censored]', 'ddd', '[censored]', 'ccc']優(yōu)化一下:
>>> strings = ['aac','ddd','aa','ccc'] >>> index = 0 >>> for string in strings:if 'aa' in string:strings[index] = '[censored]'index += 1>>> strings ['[censored]', 'ddd', '[censored]', 'ccc']繼續(xù)優(yōu)化:
內(nèi)置函數(shù)enumerate能夠迭代索引-值對(duì),其中的索引是自動(dòng)提供的。
>>> strings = ['aac','ddd','aa','ccc'] >>> for index,string in enumerate(strings):if 'aa' in string:strings[index] = '[censored]' >>> strings ['[censored]', 'ddd', '[censored]', 'ccc']反向迭代和排序后在迭代:
>>> sorted([4,2,5,1,3]) [1, 2, 3, 4, 5] >>> sorted('hello,world') #sorted返回一個(gè)列表 [',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('Hello,world')) #reversed返回一個(gè)可迭代對(duì)象, ['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H'] >>> ''.join(reversed('Hello,world')) 'dlrow,olleH' >>> sorted('aBc',key=str.lower) #按照字母表排序,可以先轉(zhuǎn)換為小寫 ['a', 'B', 'c']?
break 跳出循環(huán)
>>> from math import sqrt >>> for n in range(99,1,-1): #找出2-100的最大平方值,從100向下迭代,找到第一個(gè)平方值后,跳出循環(huán)。步長(zhǎng)為負(fù)數(shù),讓range向下迭代。root = sqrt(n)if root == int(root): #開(kāi)平方為整print(n)break81?
while True/break
>>> while True: #while True導(dǎo)致循環(huán)永不結(jié)束word = input('enter your name:')if not word:break #在if語(yǔ)句中加入break可以跳出循環(huán)print(word)enter your name:aa aa enter your name:bb bb enter your name: >>>?
簡(jiǎn)單推導(dǎo)
列表推導(dǎo)式一種從其他列表創(chuàng)建列表的方式,類似于數(shù)學(xué)中的集合推導(dǎo)。
>>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]打印能被3整除的平方值
>>> [x*x for x in range(10) if x%3 == 0] [0, 9, 36, 81]使用多個(gè)for部分,將名字的首字母相同的男孩和女孩配對(duì)。
>>> girls = ['aaa','bbb','ccc'] >>> boys = ['crde','bosy','adeb'] >>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]] ['crde+ccc', 'bosy+bbb', 'adeb+aaa']上面的代碼還能繼續(xù)優(yōu)化:
>>> girls = ['aaa','bbb','ccc'] >>> boys = ['crde','bosy','adeb'] >>> letterGrils = {} >>> for girl in girls:letterGrils.setdefault(girl[0],[]).append(girl) #每項(xiàng)的鍵都是一個(gè)字母,值為該字母開(kāi)頭的女孩名字組成的列表>>> print([b+'+'+g for b in boys for g in letterGrils[b[0]]]) ['crde+ccc', 'bosy+bbb', 'adeb+aaa']?
字典推導(dǎo)
>>> squares = {i:'{} squared is {}'.format(i,i**2) for i in range(10)} >>> squares[8] '8 squared is 64'?
轉(zhuǎn)載于:https://www.cnblogs.com/suancaipaofan/p/11070937.html
總結(jié)
以上是生活随笔為你收集整理的Python学习6——条件,循环语句的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: apt-get for ubuntu 工
- 下一篇: Oracle--plsql异常处理