1. Single branch structure
If < conditions >: < statement block >
2. Two branch structure
If < conditions >: < statement block > else: < statement block > Compact form: two branch structure for simple expressions < expression1 > If < condition > else < expression2 > guess=eval(input()) print("guess" {} ". format(" right "if guess==99 else" wrong ")
3. Condition combination
x and y #The logical sum of two conditions x and y x or y #Logical or of two conditions x and y not x #Logical negation of condition x
4. Program exception handling
num = eval(input("Please enter an integer:")) print(num**2) //When input'abc'The following error message appears: Traceback (most recent call last): File "E:/python/CalBMI.py", line 2, in <module> print(num**2) TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' //Basic use of exception handling: try: <Statement block1> except <Exception type>:(Exception type can not be written) <Statement block2> try: num = eval(input("Please enter an integer:")) print(num**2) except TypeError: print("Input is not an integer") //Advanced use of exception handling: try: <Statement block1> except: <Statement block2> else: <Statement block3> finally: <Statement block4> #finally Corresponding statement block4Certain execution #else Corresponding statement block3Execute when no exception occurs
1. Ergodic cycle
- Extract the elements one by one from the traversal structure and put them in the loop variable
for <Loop variable> in <Ergodic structure> <Sentence> 1)Count cycle: for i in range(1,6,2): print("Hello:",i) Hello: 1 Hello: 3 Hello: 5 2)String traversal loop: for c in s: <Statement block> for c in "python": print(c,end=",") p,y,t,h,o,n, 3)List traversal loop: for item in ls: <Statement block> for item in [123,"PY",456]: print(item,end=",") 123,PY,456, 4)File traversal loop: for line in fi: #fi is a file identifier, traversing each line to generate a loop <Statement block> for line in fi: print(line) #Read one line of file at a time //good //very good //Very nice
2. Condition cycle
1)
a=3 while a>0: a+=1; print(a) 4 5 ... (here CTRL + C Exit execution)
2) cycle control reserved word
- break jumps out and ends the current cycle
- Continue to end the current cycle and continue to execute the subsequent cycles
3. Advanced usage of circulation
for <variable> in <Ergodic structure>: <Statement block1> else: <Statement block2> while <condition>: <Statement block1> else: <Statement block2>
- When the loop is not exited by the break statement, the else statement block is executed
- else statement block as reward for "normal" completion cycle
- Here, the use of else is similar to that in exception handling
for c in "PYTHON": if c =="T": continue; print(c,end="") else: print("Normal exit") //Output is:PYTHONNormal exit