Alibabacloud.com offers a wide variety of articles about nested while loops python, easily find your nested while loops python information here online.
Jump out of the multilayer loop: three-layer loop, the innermost layer directly jumps out 3 layersIn Python, the function runs to return and stops, so you can use this feature to write functions as functions to terminate multiple loops
1234567891011121314
defwork():foriinrange(5):print("i=", i)forjinrange(5):print("--j=", j)forkinrange(5):if k2:print("------>k=", k)else:return i,j,kprint(wo
A simple for statement loops through all the keys of the dictionary, just as it does with sequences:
In [1]: D = {' X ': 1, ' Y ': 2, ' Z ': 3} in
[2]: for key in D:
...: print key, ' corresponds to ', D[key]
...:
Y corresponds to 2
x corresponds to 1
z corresponds to 3
Before python2.2, you can only use the dictionary methods such as Beys to get the keys (because the dictionary is not allowed to iterate directly). If you only need val
Python basics for. Net programmers-judgment conditions and loops [Fourth Day]Today, I learned how to judge conditions and perform loop operations in Python. 1. boolean variables: you must understand the bool variables before learning and determining conditions. In Python, the bool variables are similar to those in C la
How does python for get the number of current loops?
From: http://markmail.org/message/ryfven2i75kgsrsm
Enumerate is a new built-in function in Python 2.3. Its English description is as follows:
Enumerate (iterable)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. the next () method oft
the information of a blog, followed by the regular to extract the content we need to5. Regular expressions title= re.compile (' title1= Re.findall (title,html)HTML is the entire Web page all the code document, these two lines of code will be in this page all the blog title in the Title1 listwhere 6. Link Databasedb = Pymysql.connect ("127.0.0.1", "root", "root", "crawler", charset= "UTF8") #打开数据链接,Pymysql.connect () The first four parameters I will not say more, charset= "UTF8" This parameter c
, +, + , + ]
>>> [(x, y) for x in range (1,3) for y in range (4,6)]
[(1, 4), (1, 5), (2, 4), (2, 5)]
Assert assertThe following statement is true, otherwise assertionerror appearsUsed to check a condition, and if it is true, do nothing. If it is false, it throws a Asserterror and contains an error message.For example:
py>x=23py>assertx>0,"xisnotzeroornegative"py>assertx%2==0,"xisnotanevennumber"Traceback(mostrecentcalllast):File"",line1,inAssertionError
', ' name '), (' Qiwsir.github.io ', ' site ')]
>>> dict (temp) #这是函数dict () function to convert the above list to dictionary{' Python ': ' Lang ', ' Qiwsir.github.io ': ' Site ', ' qiwsir ': ' Name '}
At this point, do you understand the relationship between the zip () and the loop? With it you can make some loops simpler. In particular, when reading a database with
=SYS.ARGV[1] # #相当于shell中的 The first parameter of the script commandFILE2=SYS.ARGV[2] # #相当于shell中的 The second argument of the $ $ script commandX=open (File1)Y=open (File2, ' W ')For I in x:Y.writelines (i)Y.close ()X.close ()################################Module (/usr/lib64/python2.7/)Import Module Name # #导入模块中所有函数Module name. function () # #调用函数The name of the function. VariableFrom Module name Import function # # #只导入模块中的一个函数From NB Import StarImport module, module, module # # #导入多个模块逗号隔开
ConditionsSimilar to other languages, Python uses if...elif...else to form branches, supporting three-mesh operators? : There is no switch in Python, but the indentation feature makes the IF...ELIF...ELSE structure as easy to readLoop controlIn Python, in addition to the Break,continue two general loop control statements, there is a pass that performs an empty op
statement is:
If
If statement execution has a feature, it is judged from the top down, if in a certain judgment is true, the statement corresponding to the sentence after the execution, ignore the remaining elif and else, so please test and explain why the following program prints the teenager:
Age =
>= 6:
print ' teenager '
elif age >=:
print ' adult '
else:
print ' Kid
If judgment conditions can also be abbreviated, such as writing:
If x:
print ' T
classes.Del:del keyword Delete is two things, one is the object's reference , and the other is the name of the variable, Del is not deleted value , in Python is There is no way to delete the value, and the Python interpreter is responsible for the memory collection.The. EXEC: the keyword exec executes the python code stored in the string and can provide the nam
the programSummaryThe colon after the IF statementThe affiliation is represented by the indentation of four spaces and cannot be indented in PythonIf StatementElif StatementElif StatementElseStatementFor loopFor a in [3,4.4, ' life ']: print aFor a in range: print a**2//* * means powerWhile loopWhile I Break the LoopFor I in range (10): Continue Print IFor I in range: if i = = 2: Break Print IFunctionFirst, we'll define a function to illustrate the function.Def square_
=[1,2,3]>>> x==yDisplay: True>>> x==zDisplay: True>>> x is yDisplay: True>>> X is ZDisplay: False3, in, membership operator>>> if ' s ' in Name:>>> print (' Your name contains the letter "s")>>> Else:>>> print (' Your name does not contain ' s '. ')4. Assert, Assert>>>age=-1>>> assert 0Showing: assertionerror:the must be realistic5. While loop>>> x=1>>> while x>>> Print (x)>>> x+=16. For loop>>> numbers=[0,1,2,3,4,5,6,7]>>> for number in numbers:>>> Print (number)
Print the 9-9 multiplication table using Python loops (including while for) and pythonwhile
I. Print the 9-9 multiplication table in a for Loop
# Note: Due to the poor control of indentation in the browser, please forgive me. images will be imported later.
1.1 lower left corner
For I in range (1, 10 ):
For j in range (1, I + 1 ):
Print ('% d * % d = % 2d \ t' % (j, I, I * j), end = '')Print ()
:
1.2 bott
In a single-layer loop exit, use break to exit, so what is the multi-layer loop? Witty people use the flag identifier in the way, for example:a=['a', 1,2,3,4]b=['b', 1,2,3,4]c=['C', 1,2,3,4]d=['D', 1,2,3,4]break_flag=0 whilebreak_flag==0:y_n=input ('A,yes or No:') ifY_n = ='N': Break elifY_n = ='y': forIinchA:Print(i) whileBreak_flag = =0:y_n_2=input ('B,yes or No:') ify_n_2=='N': Print('Exit') Break_flag=1elify_n_2=='y': forIinchB:
While and for loopsGeneral formatWhile ElseThe Else section is optional and is executed if control leaves the Wihle and there is no break.Break: Jump out of the nearest loopContinue: Jumps to the beginning of the nearest loopPass: Nothing is done, just a placeholderelse: It will only execute if it encounters a breakFor loopGeneral formatFor ElseThe For loop also supports an else part that also encounters a break to executeBasic applicationsFor x in [' Spam ', ' eggs ', ' ham ']:print (x);sum = 0
If Loop: two optionsExample 1:1 a=2if a:3 print ('the Number less than')4Else:5 Print ( ' Thank you! ')Example 2:While loop: Repeats a function multiple timesExample 11 greetings=12 while greetings3: #这里记住了是 3 print ('hello! '*greetings)4 greetings=greetings+12 . Pyhello! Hello!hello! Hello!hello!hello!Example 2 For loop: Iterate through every element in the listExample 1 1 names=[ " a ", " b ", " c 2 for name in names: 3 Print ( hello! +name) 1 . Pyhello! Ahel
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.