取得字典中任意的鍵-值對
>>> x={'a':1,'b':2} >>> key,value=x.popitem() >>> key,value ('a', 1) >>> del x[key] Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> del x[key] KeyError: 'a' >>> x {'b': 2} >>> x[key]=value >>> x {'a': 1, 'b': 2} >>> del x[key]
增量賦值
>>> x=2 >>> x+=1 >>> x*=2 >>> x >>> fnord='foo' >>> fnord+='bar' >>> fnord*=2 >>> fnord 'foobarfoobar'
條件執行if語句
>>> name=raw_input('?') ?Yq Z >>> if name.endswith('Z'): \ print 'Hello,Mr.Z' Hello,Mr.Z
else子句
>>> name=raw_input('what is your name?') what is your name?Yq Z >>> if name.endswith('Z'): print 'Hello,Mr.Z' else: print 'Hello,stranger' Hello,Mr.Z
elif子句
>>> num=input('Enter a number: ') Enter a number: 5 >>> if num>0: print 'The number is position' elif num<0: print 'The number is negative' else: print 'The number is zero' The number is position
條件巢狀語句
>>> name=raw_input('What is your name?') What is your name?Yq Z >>> if name.endswith('Yq'): if name.startswith('Z'): print 'Hello,Yq Z' elif name.startswith('K'): print 'Hello,Zyq' else: print 'Hello,Yq' else: print 'Hello,stranger' Hello,stranger
>>> number=input('Enter a number between 1 and 10:') Enter a number between 1 and 10:6 >>> if number<=10 and number>=1: print 'Great!' else: print 'Wrong!' Great!
>>> age=10 >>> assert 0<age<100 >>> age=-1 >>> assert 0<age<100 Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> assert 0<age<100 AssertionError
while迴圈
>>> x=1 >>> while x<=100: print x x+=1
>>> while not name: name=raw_input('Please enter your name:') print 'Hello,%s !' % name Please enter your name:zyq Hello,zyq !
for迴圈
>>> words=['this','is','an','ex','parrot'] >>> for word in words: print word this is an ex parrot >>> range(0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for i in range(1,8): print i 2 4 6
字典迴圈(迭代)
>>> d={'x':1,'y':2,'z':3} >>> for key in d: print key,'corresponds to',d[key] y corresponds to 2 x corresponds to 1 z corresponds to 3
for迴圈
>>> names=['Anne','Beth','George','Damon'] >>> ages=[12,19,18,20] >>> for i in range(len(names)): print names[i],'is',ages[i],'years old' Anne is 12 years old Beth is 19 years old George is 18 years old Damon is 20 years old
字典迴圈(迭代)
>>> zip(names,ages) [('Anne', 12), ('Beth', 19), ('George', 18), ('Damon', 20)] >>> for name,age in zip(names,ages): print name,'is',age,'years old' Anne is 12 years old Beth is 19 years old George is 18 years old Damon is 20 years old >>> zip(range(5),xrange(100)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
並行迭代
>>> d [1, 2, 4, 4] >>> for x in d: if x==4: d[d.index(x)]=6 >>> d [1, 2, 6, 6] >>> S=['skj','kiu','olm','piy'] >>> index=0>>> for s1 in S: if 'k' in s1: S[index]='HH' index+=1 >>> S ['HH', 'HH', 'olm', 'piy']>>> for index,s2 in enumerate(S): #enumerate函数提供索引-值对 if 'H' in s2: S[index]='DF' >>> S ['DF', 'DF', 'olm', 'piy']
>>> sorted([4,3,6,8,3]) [3, 3, 4, 6, 8] >>> sorted('Hello,world!') ['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('Hello,world!')) ['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H'] >>> ''.join(reversed('Hello,world!')) '!dlrow,olleH'
編號迭代
>>> for n in range(99,0,-1): m=sqrt(n) if m==int(m): print n break
翻轉、排序迭代
>>> while True: word=raw_input('Please enter a word:') if not word:break print 'The word was '+word Please enter a word:f The word was f Please enter a word:
break跳出迴圈
>>> for n in range(99,81,-1): m=sqrt(n) if m==int(m): print m break else: print 'h' h
while True/break
>>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x*x for x in range(10) if x%3==0] [0, 9, 36, 81] >>> [(x,y) for x in range(3) for y in range (3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] >>> result=[] >>> for x in range(3): for y in range(3): result.append((x,y)) >>> result [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] >>> girls=['Alice','Bernice','Clarice'] >>> boys=['Chris','Arnold','Bob'] >>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]] ['Chris+Clarice', 'Arnold+Alice', 'Bob+Bernice']##跳出迴圈
>>> if name=='Nsds': print 'Welcome!' elif name=='UK': #还没完 pass elif name=='Bill': print 'Access Denied' else: print 'Nobody!'while True/break
>>> x=['Hello','world'] >>> y=x >>> y[1]='Python' >>> x ['Hello', 'Python'] >>> del x >>> y ['Hello', 'Python']循環中的else語句
>>> exec "print 'Hello,world!'" Hello,world! >>> from math import sqrt >>> exec "sqrt=1" >>> sqrt(4) Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> sqrt(4) TypeError: 'int' object is not callable #增加一个字典,起到命名空间的作用 >>> from math import sqrt >>> scope={} >>> exec 'sqrt=1' in scope >>> sqrt(4) 2.0 >>> scope['sqrt']列表推導式-輕量級循環
>>> len(scope)2 >>> scope.keys() ['__builtins__', 'sqrt']pass
>>> scope={} >>> scope['x']=2 >>> scope['y']=3 >>> eval('x*y',scope) >>> scope={} >>> exec 'x=2' in scope >>> eval('x*x',scope)del x和y同時指向一個列表,但是刪除x並不會影響y。刪除的只是名稱,不是清單本身(值)
rrreeeexec
注意:命名空間,稱作作用域。可以把它想像成保存變數的地方,類似不可見的字典。執行 x=1這類賦值語句時,就將鍵x和值1放在目前的命名空間內,這個命名空間一般來說都是全域命名空間。
rrreee
以上是python中條件、循環等介紹說明的詳細內容。更多資訊請關注PHP中文網其他相關文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Atom編輯器mac版下載
最受歡迎的的開源編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中