Python:Control structures: Difference between revisions

From wiki
Jump to navigation Jump to search
No edit summary
Line 21: Line 21:
except <exception>:
except <exception>:
     blockifexceptionisthrown
     blockifexceptionisthrown
else:
    blockifNOexceptionisthrown
</syntaxhighlight>
</syntaxhighlight>


Line 27: Line 29:
;except NameError
;except NameError
:The variable does not exist
:The variable does not exist
;except KeyError
:The key does not exist in the dict
;except IndexError
:The index does not exist in the list

Revision as of 11:12, 22 August 2018


Most flow control is standard. Indentation defines the code block to execute. You must be strict, all indents must be the same in a block, a mix of spaces and tabs is not allowed (unless each line uses the same mix).

if expression:
    block
else:
    otherblock


pass
No operation, use e.g. to avoid negative tests

Exception handling

To catch exceptions:

try:
    blockthatmaythowexception
except <exception>:
    blockifexceptionisthrown
else:
    blockifNOexceptionisthrown

Specifying an exception is optional but highly recommended. The exceptiontypes can be found in the python docs

except NameError
The variable does not exist
except KeyError
The key does not exist in the dict
except IndexError
The index does not exist in the list