Python は例外オブジェクトを使用して例外を表します。エラーが発生すると、例外がスローされます。例外オブジェクトが処理されない、またはキャッチされない場合、プログラムはいわゆるトレースバック (エラー メッセージ) で実行を終了します:
>>> 1/0
Traceback (most 最新の呼び出し 最後):
File "
>>> raise Exception #引发一个没有任何错误信息的普通异常 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise Exception Exception >>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise Exception('hyperdrive overload') Exception: hyperdrive overloadシステムに付属の組み込み例外クラス: >>> importExceptions>>> dir(例外)[' ArithmeticError'、'AssertionError'、'AttributeError'、'BaseException'、'BufferError'、'BytesWarning'、'DeprecationWarning'、'EOFError'、'EnvironmentError'、'Exception'、'FloatingPointError'、'FutureWarning'、'GeneratorExit' , 'IOError '、'ImportError'、'ImportWarning'、'IndentationError'、'IndexError'、'KeyError'、'KeyboardInterrupt'、'LookupError'、'MemoryError'、'NameError'、'NotImplementedError'、'OSError'、' OverflowError'、'PendingDeprecationWarning'、'ReferenceError'、'RuntimeError'、'RuntimeWarning'、'StandardError'、'StopIteration'、'SyntaxError'、'SyntaxWarning'、'SystemError'、'SystemExit'、'TabError'、'TypeError' 、'UnboundLocalError '、'UnicodeDecodeError'、'UnicodeEncodeError'、'UnicodeError'、'UnicodeTranslateError'、'UnicodeWarning'、'UserWarning'、'ValueError'、'Warning'、'WindowsError'、'ZeroDivisionError'、'__doc__'、' __name__'、'__package__']すごい!一般的に使用される組み込み例外クラスが多数あります。 カスタム例外 組み込み例外クラスはほとんどの状況をカバーしており、多くの要件には十分ですが、独自の例外クラスを作成する必要がある場合もあります。 他の一般的なクラスと同様に、直接的または間接的に Exception クラスから継承するようにしてください。次のようになります: >>> class someCustomExcetion(Exception):pass もちろん、このクラスにいくつかのメソッドを追加することもできます。 例外のキャッチ try/excel を使用して例外のキャッチと処理を実装できます。 ユーザーが 2 つの数値を入力してそれらを除算できるプログラムを作成するとします。 #どうですか?今回はさらにフレンドリーです ユーザーとの対話中に例外情報をユーザーに見せたくない場合は、デバッグ中に例外を発生させた方がよいでしょう。 「ブロック」メカニズムをオン/オフにするにはどうすればよいですか?
x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y #运行并且输入 Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in <module> print x/y ZeroDivisionError: integer division or modulo by zero 为了捕捉异常并做出一些错误处理,可以这样写: try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #再来运行 >>> Enter the first number: 10 Enter the second number: 0
複数のexcel句
上記のプログラムを実行し(2つの数値を入力して割り算を計算する)、上記の内容を入力すると、別の例外が生成されます:
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #现在打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
OK!この状況を処理する例外ハンドラーを追加できます:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #运行输入: >>> Enter the first number: 10 Enter the second number: 'hello.word' #输入非数字 Traceback (most recent call last): File "I:\Python27\yichang", line 4, in <module> print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息数字を入力してください! 1 つのブロックで複数の例外をキャッチ もちろん、1 つのブロックを使用して複数の例外をキャッチすることもできます:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!" #再来运行: >>> Enter the first number: 10 Enter the second number: 'hello,word'"
すべての例外をキャッチ
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!エラーが発生しました! End 心配しないでください。ユーザーが誤って間違ったものを入力しました。情報、もう一度参加するチャンスを与えてもらえますか? 負けたときに確実に終了するようにループを追加できます:

pythonusesahybridapproach、コンコイリティレーショントビテコードと解釈を組み合わせて、コードコンピレッドフォームと非依存性bytecode.2)

keydifferencesは、「for」と「while "loopsare:1)" for "for" loopsareideal forterating overencesonownowiterations、while2) "for" for "for" for "for" for "for" for "for" for for for for "wide" loopsarebetterunuinguntinunuinguntinisisisisisisisisisisisisisisisisisisisisisisisisisisisations.un

Pythonでは、さまざまな方法でリストを接続して重複要素を管理できます。1)オペレーターを使用するか、すべての重複要素を保持します。 2)セットに変換してから、リストに戻ってすべての重複要素を削除しますが、元の順序は失われます。 3)ループを使用するか、包含をリストしてセットを組み合わせて重複要素を削除し、元の順序を維持します。

fasteStMethodDodforListConcatenationinpythOndontsonistize:1)forsmallLists、operatorisefficient.2)forlargerlists、list.extend()orlistcomlethingisfaster、withextend()beingmorememory-efficient bymodifyigniviselistinistin-place。

to insertelementsIntopeaseThonList、useappend()toaddtotheend、insert()foraspificposition、andextend()formultipleElements.1)useappend()foraddingsingleitemstotheend.2)useintert()toaddataspecificindex、cont'slowerforforgelists.3)

PythonListsareimplementedasdynamicarrays、notlinkedlists.1)they restorediguourmemoryblocks、それはパフォーマンスに影響を与えることに影響を与えます

pythonoffersfourmainmethodstoremoveelements fromalist:1)removesthefirstoccurrenceofavalue、2)pop(index(index(index)removes regvess returnsaspecifiedindex、3)delstatementremoveselementselementsbyindexorseLice、および4)clear()

toresolvea "許可denided" errors whenrunningascript、sofflowthesesteps:1)checkandadaddadaddadadaddaddadadadaddadaddadaddadaddaddaddaddaddadaddadaddaddaddaddadaddaddaddadadaddadaddadaddadadisionsisingmod xmyscript.shtomakeitexexutable.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

SublimeText3 中国語版
中国語版、とても使いやすい

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター
