Get any key-value pair in the dictionary
>>> 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]
Incremental assignment
>>> x=2 >>> x+=1 >>> x*=2 >>> x >>> fnord='foo' >>> fnord+='bar' >>> fnord*=2 >>> fnord 'foobarfoobar'
Conditional execution if statement
>>> name=raw_input('?') ?Yq Z >>> if name.endswith('Z'): \ print 'Hello,Mr.Z' Hello,Mr.Z
else clause
>>> 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 clause
>>> 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
Conditional nested statement
>>> 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 loop
>>> 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 loop
>>> 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
Dictionary loop (iteration)
>>> 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
Parallel iteration
>>> 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)]
Numbered iteration
>>> 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']
Flip, sort iteration
>>> 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'
break out of the loop
>>> for n in range(99,0,-1): m=sqrt(n) if m==int(m): print n break
while True/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:
else statement in loop
>>> for n in range(99,81,-1): m=sqrt(n) if m==int(m): print m break else: print 'h' h
List comprehension-lightweight loop
>>> [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']
pass
>>> if name=='Nsds': print 'Welcome!' elif name=='UK': #还没完 pass elif name=='Bill': print 'Access Denied' else: print 'Nobody!'
del x and y point to a list at the same time, but deleting x does not will affect y. Only the name is deleted, not the list itself (value)
>>> x=['Hello','world'] >>> y=x >>> y[1]='Python' >>> x ['Hello', 'Python'] >>> del x >>> y ['Hello', 'Python']
exec
>>> 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']
Note: The namespace is called a scope. Think of it as a place to hold variables, similar to an invisible dictionary. When executing an assignment statement such as x=1, the key x and value 1 are placed in the current namespace. This namespace is generally the global namespace.
>>> len(scope)2 >>> scope.keys() ['__builtins__', 'sqrt']
eval evaluation
>>> scope={} >>> scope['x']=2 >>> scope['y']=3 >>> eval('x*y',scope) >>> scope={} >>> exec 'x=2' in scope >>> eval('x*x',scope)
The above is the detailed content of Introduction to conditions, loops, etc. in python. For more information, please follow other related articles on the PHP Chinese website!

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

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
