Difference between revisions of "Python:Control structures"

From wiki
Jump to navigation Jump to search
m
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 all exceptions (not wise)
+
To catch exceptions:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
try:
 
try:
     block
+
     blockthatmaythowexception
except:
+
except <exception>:
 
     blockifexceptionisthrown
 
     blockifexceptionisthrown
 
</syntaxhighlight>
 
</syntaxhighlight>
  
You better only catch the exceptions you expect. You can choose from the available exceptions [https://docs.python.org/3/library/exceptions.html#exception-hierarchy]
+
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 09: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