Python Error and Exception Concepts (General)
1. How to handle errors and exceptions
Common Errors
a: NameError
if True: SyntaxError
f = oepn('1.txt'): IOError
10/0: ZeropisionError
a = int('d'): ValueError
Program Running interruption: KeyboardInterrupt
2.Python-use try_except to handle exceptions (1)
try: try_suite except Exception [e]: exception_block
try is used to capture errors in try_suite, and Handle the error to except
except is used to handle exceptions. If handling exceptions is consistent with setting captured exceptions, use exception_block to handle exceptions
# case 1 try: undef except: print 'catch an except'
# case 2 try: if undef except: print 'catch an except'
case1: The exception can be caught because it is a runtime error
case2: The exception cannot be caught because it is a syntax error and a pre-run error
--
# case 3 try: undef except NameError,e: print 'catch an except',e
# case 4 try: undef except IOError,e: print 'catch an except',e
case3: The exception can be caught because the catch NameError exception is set
case4: The exception cannot be caught because Setting IOError will not handle NameError
Example
import random num = random.randint(0, 100) while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print '\n'
3. Python uses try_except to handle exceptions (2)
try -except: handle multiple exceptions
try: try_suite except Exception1[e]: exception_block1 except Exception2[e]: exception_block2 except ExceptionN[e]: exception_blockN
4. Python-try_finally uses
try: try_suite finally: do_finally
If the try statement does not catch the error, the code executes the do_finally statement
If the try statement catches an error, the program first executes the do_finally statement, and then hands the captured error to the python interpreter for processing
5. Python -try-except-else-finally
try: try_suite except: do_except finally: do_finally
If the try statement does not catch the exception, after executing the try code segment, execute finally
If try catches the exception, first executes except to handle the error, and then executes finally
6. Python-with_as statement
with context [as var]: with_suite
with statement is used to replace try_except_finall statement to make the code more concise
The context expression returns an object
var is used to save the context return object, a single return value or a tuple
with_suite uses var variables to operate on the context return object
The essence of the with statement is context management:
Context management protocol: Contains methods
__enter__()
and__exit()__
. Objects that support this protocol must implement these two methodsContext manager: defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block
Enter the context manager: call Manager
__enter__
method, if the as var statement is set, the var variable accepts__enter__()
method return valueExit the context manager: call Manager
__exit__
Method
class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_val if __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
whith statement application scenario:
File operation
Mutual exclusion objects between process threads, such as mutex locks
Other objects that support context
2. Standard exceptions and Automatically with exception
1. Python-assert and raise statements
rais statement
reise statement is used Actively throw exceptions
Syntax format: raise[exception[,args]]
exception: exception class
args: Tuple describing exception information
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
assert statement
Assertion statement: The assert statement is used to check whether the expression is true. If it is false, an AssertionError is raised.
Syntax format: assert expression[,args]
experession: expression
args: description information of the judgment condition
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-Standard Exceptions and custom exceptions
Standard exceptions
Python built-in exceptions already exist before the program is executed
Custom exceptions:
Python allows custom exceptions, Used to describe exceptions not involved in python
Custom exceptions must inherit the Exception class
Custom exceptions can only be actively triggered
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.message try: raise CustomError('test CustomError') except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)
For more articles related to Python errors and exception concepts, please pay attention to the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

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