Else in other languages can only be combined with if, which is our common if...else, but Python gives new claims to else. It can be used in tandem with while, for, and try.
Here we describe the effects of using while concatenation.
count=0 while count>12: if (11>0): print( " established ") break count+=1else: Print (' not established '# when the while condition is not set, jump directly to the output
For loops and while usages
def forelse (): = [up] for in C: print(i) Else : Print (" output "# when the For loop ends, the statement is output
Use of Try
def tryelse (): Try : = except TypeError as reason: print(" error " Else: print(" come to me " # The method is executed when the statement in the try block executes correctly.
With ...: usage
#The first form of a notationdefWithas ():Try: F= Open ("text. txt") Print(F.read ()) F.close ()exceptOSError as Reason:Print("Read Error") Else: Print("Complete")#the second way of writing with, be sure not to forget: Ohdefwithas2 ():Try: With open ("text. txt") as F:Print(F.read ()) F.close ()exceptOSError as Reason:Print("Read Error") Else: Print("Complete")
Why use with, because sometimes we may use open (file) when opening a file, perhaps this file does not exist, then this time will be an error, and we may unload this method in a try except finally such a statement, And in the finally there may be added f.close () such a statement, but we do not open an F file at this time, because this file does not exist, so there is no need to close this file. That's when we used the with.
Error codes Show:
defwithas1 ():Try: F= Open ("text 1.txt")#The file does not exist Oh Print(F.read ())exceptOSError as Reason:Print("Read Error") finally: F.close ()#--------------Error OutputRead Error Traceback (most recent call last): File"e:/python/day-2/whileelse.py", line 46,inch<module>withas1 () File"e:/python/day-2/whileelse.py", line 44,inchwithas1 f.close () unboundlocalerror:local variable'F'referenced before assignment>>>
From the error output we can see that the reported error is a local variable error, that is, F does not exist, that is, did not open the file.
Python, using While...else and For...else, and Try...else, plus using the WITH keyword