Difference between revisions of "Python:Control structures"
Jump to navigation
Jump to search
Line 42: | Line 42: | ||
except <exception>: | except <exception>: | ||
blockifexceptionisthrown | blockifexceptionisthrown | ||
+ | except <exception2>: | ||
+ | blockifexception2isthrown | ||
else: | else: | ||
− | + | blockif_NO_exceptionisthrown | |
</syntaxhighlight> | </syntaxhighlight> | ||
NOTE: elif is not allowed here. | NOTE: elif is not allowed here. | ||
Specifying an exception is optional but highly recommended (Easier to ask for forgiveness than permission aka EAFP) and it is said to be faster. However, take care you don't forgive real faults. | Specifying an exception is optional but highly recommended (Easier to ask for forgiveness than permission aka EAFP) and it is said to be faster. However, take care you don't forgive real faults. | ||
+ | |||
+ | If more exceptions are defined with 1 try only 1 exception block will be executed, | ||
The exception-types can be found in the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy python docs] | The exception-types can be found in the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy python docs] |
Revision as of 17:15, 15 June 2022
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).
You can define you own Python:Functions too.
if expression:
block
elif expression:
block
else:
otherblock
for var1 in itterable: # keys if itterable is a dict
block
if somethinghappens:
break
while expression:
block
if somethinghappens:
continue
break
- Stop looping immediately. Jump to the next statement after the loop.
continue
- Stop the current iteration immediately and jump the the top of the loop, do the next iteration.
pass
- No operation, use e.g. to avoid negative tests
var1 = ( x if <condition> else y )
- No operation, use e.g. to avoid negative tests
Exception handling
To catch exceptions:
try:
blockthatmaythowexception
except <exception>:
blockifexceptionisthrown
except <exception2>:
blockifexception2isthrown
else:
blockif_NO_exceptionisthrown
NOTE: elif is not allowed here.
Specifying an exception is optional but highly recommended (Easier to ask for forgiveness than permission aka EAFP) and it is said to be faster. However, take care you don't forgive real faults.
If more exceptions are defined with 1 try only 1 exception block will be executed,
The exception-types 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