Python:Control structures: Difference between revisions
Jump to navigation
Jump to search
mNo edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
[[Category:Python]] | [[Category:Python]] | ||
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) | 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). | ||
<syntaxhighlight lang=python> | <syntaxhighlight lang=python> | ||
| Line 9: | Line 9: | ||
otherblock | otherblock | ||
</syntaxhighlight> | </syntaxhighlight> | ||
;<code>pass</code> | ;<code>pass</code> | ||
| Line 14: | Line 15: | ||
==Exception handling== | ==Exception handling== | ||
To catch | To catch exceptions: | ||
<syntaxhighlight lang=python> | <syntaxhighlight lang=python> | ||
try: | try: | ||
blockthatmaythowexception | |||
except: | except <exception>: | ||
blockifexceptionisthrown | blockifexceptionisthrown | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Specifying an exception is optional but highly recommended. The exceptiontypes can be found in the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy python docs] | |||
;except NameError | ;except NameError | ||
:The variable does not exist | :The variable does not exist | ||
Revision as of 07:57, 17 July 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
Specifying an exception is optional but highly recommended. The exceptiontypes can be found in the python docs
- except NameError
- The variable does not exist