日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python学习6——条件,循环语句

發(fā)布時間:2023/12/18 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python学习6——条件,循环语句 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

條件語句

真值也稱布爾值。

用作布爾表達式時,下面的值都將被視為假:False None? 0? ?""? ?()? ?[]? ?{}。

布爾值True和False屬于類型bool,而bool與list、str和tuple一樣,可用來轉(zhuǎn)換其他的值。

>>> bool('I think,therefore I am') True >>> bool(10) True >>> bool('') False >>> bool(0) False

?

if語句

>>> name = input('What is your name?') What is your name?Gumby >>> if name.endswith('Gumby'):print(name)Gumby

如果條件(if和冒號之間的表達式)是前面定義的真,就執(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

?

比較運算符:

表達式描述
x == yx等于y
x < yx小于y
x > yx大于y
x >= y?x大于或等于y
x <= yx小于或等于y
x != yx不等于y
x is yx和y是同一個對象
x is not yx和y是不同的對象
x in yx是容器y的成員
x not in yx不是容器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檢查兩個對象是否相同(不是相等),變量x和y指向同一個列表,而z指向另一個列表(即使它們包含的值是一樣的),這兩個列表雖然相等,但并非同一個列表。

?

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' #字符串對斷言做出說明 Traceback (most recent call last):File "<pyshell#49>", line 1, in <module>assert 0 < age < 11,'the age must be realistic' #字符串對斷言做出說明 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個位置,將把這個位置視為結(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)])

?

并行迭代:

同時迭代2個序列。

>>> 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個序列縫合起來,并返回一個由元組組成的序列。

>>> 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 old

zip函數(shù)可以縫合任意數(shù)量的序列,當序列的長度不同時,zip函數(shù)將在最短的序列用完后停止縫合。

>>> list(zip(range(5),range(10))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

?

迭代時獲取索引:

>>> 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能夠迭代索引-值對,其中的索引是自動提供的。

>>> 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返回一個列表 [',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('Hello,world')) #reversed返回一個可迭代對象, ['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向下迭代,找到第一個平方值后,跳出循環(huán)。步長為負數(shù),讓range向下迭代。root = sqrt(n)if root == int(root): #開平方為整print(n)break81

?

while True/break

>>> while True: #while True導致循環(huán)永不結(jié)束word = input('enter your name:')if not word:break #在if語句中加入break可以跳出循環(huán)print(word)enter your name:aa aa enter your name:bb bb enter your name: >>>

?

簡單推導

列表推導式一種從其他列表創(chuàng)建列表的方式,類似于數(shù)學中的集合推導。

>>> [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]

使用多個for部分,將名字的首字母相同的男孩和女孩配對。

>>> 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) #每項的鍵都是一個字母,值為該字母開頭的女孩名字組成的列表>>> print([b+'+'+g for b in boys for g in letterGrils[b[0]]]) ['crde+ccc', 'bosy+bbb', 'adeb+aaa']

?

字典推導

>>> 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——条件,循环语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。