Python:Control structures: Difference between revisions

From wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 16: Line 16:
     block
     block
     if somethinghappens:
     if somethinghappens:
         break<syntaxhighlight lang=python>
         break


while expression:
while expression:
     block
     block
     if somethinghappens:
     if somethinghappens:
         break
         continue
</syntaxhighlight>
</syntaxhighlight>


;<code>break</code>
:Stop looping immediately. Jump to the next statement after the loop.
;<code>continue</code>
:Stop the current iteration immediately and jump the the top of the loop, do the next iteration.
;<code>pass</code>
;<code>pass</code>
:No operation, use e.g. to avoid negative tests
:No operation, use e.g. to avoid negative tests

Revision as of 11:16, 13 January 2021


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
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