Python:Control structures: Difference between revisions

From wiki
Jump to navigation Jump to search
mNo edit summary
No edit summary
 
(19 intermediate revisions by the same user not shown)
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).
 
You can define you own [[Python:Functions]] too.


<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
if expression:
if expression:
    block
elif expression:
     block
     block
else:
else:
     otherblock
     otherblock
for var1 in itterable:  # keys if itterable is a dict
    block
    if somethinghappens:
        break
while expression:
    block
    if somethinghappens:
        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
;<code>var1 = ( x if <condition1> elif <condition2> y else z )</code>
:Different way to assign a value conditionally. () only needed if spread over more lines.


==Exception handling==
==Exception handling==
To catch all exceptions (not wise)
 
Exceptions are used a lot by python programmers. The mantra is: "Easier to ask for forgiveness than permission" aka EAFP; and it is said to be faster.
 
To catch exceptions:
<syntaxhighlight lang=python>
<syntaxhighlight lang=python>
try:
try:
     block
     blockthatmaythowexception
except:
except <exception>:
     blockifexceptionisthrown
     blockifexceptionisthrown
except <exception2> as ex:
    blockifexception2isthrown
else:
    blockif_NO_exceptionisthrown
</syntaxhighlight>
</syntaxhighlight>
NOTE: elif is not allowed here.


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 a specific exception is optional but highly recommended. However, take care you don't forgive real faults.
 
If more exceptions are defined with 1 try only 1 exception block will be executed,
 
For reporting where the exception happened use [[#traceback]].
 
;except <exception> as ex
:Puts the exception result in ex. ex.message has the reason for the exception.
 
;type(ex)
:The exception class
 
;except Exception
:Catches any exception


;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
A full list of exception-classes can be found in the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy python docs]
;raise <Exception>(<text>)
:Raise an <Exception> exception, <Exception>-class must exist, <text> is up to you.
===Traceback===
Show where things went wrong
<syntaxhighlight lang=python>
import traceback
tracetext = traceback.format_exc()  # Return info as string
traceback.print_exc()  # Print the info
</syntaxhighlight>
==Warnings==
[https://docs.python.org/3/library/warnings.html Warnings] are a subcategory of Exceptions for problems that do not break the script. E.g. for deprecated modules, division by 0 etc.
After importing the warnings package you can do things like
;warnings.simplefilter(action='ignore', category=UserWarning)
:Ignore warnings in a specific category.
;warnings.filterwarnings("error")
:Turn warnings into exceptions
;warnings.resetwarnings()
:Reset to the default handling of warnings
Example:
<syntaxhighlight lang=python>
import warnings
...
...
warnings.simplefilter(action='ignore', category=UserWarning)
<code that throws warning>
warnings.resetwarnings()
</syntaxhighlight>
This way the warning settings are restored after the known one has been passed

Latest revision as of 09:55, 29 July 2026


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 <condition1> elif <condition2> y else z )
Different way to assign a value conditionally. () only needed if spread over more lines.


Exception handling

Exceptions are used a lot by python programmers. The mantra is: "Easier to ask for forgiveness than permission" aka EAFP; and it is said to be faster.

To catch exceptions:

try:
    blockthatmaythowexception
except <exception>:
    blockifexceptionisthrown
except <exception2> as ex:
    blockifexception2isthrown
else:
    blockif_NO_exceptionisthrown

NOTE: elif is not allowed here.

Specifying a specific exception is optional but highly recommended. However, take care you don't forgive real faults.

If more exceptions are defined with 1 try only 1 exception block will be executed,

For reporting where the exception happened use #traceback.

except <exception> as ex
Puts the exception result in ex. ex.message has the reason for the exception.
type(ex)
The exception class
except Exception
Catches any exception
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

A full list of exception-classes can be found in the python docs

raise <Exception>(<text>)
Raise an <Exception> exception, <Exception>-class must exist, <text> is up to you.

Traceback

Show where things went wrong

import traceback
tracetext = traceback.format_exc()   # Return info as string
traceback.print_exc()  # Print the info

Warnings

Warnings are a subcategory of Exceptions for problems that do not break the script. E.g. for deprecated modules, division by 0 etc.

After importing the warnings package you can do things like

warnings.simplefilter(action='ignore', category=UserWarning)
Ignore warnings in a specific category.
warnings.filterwarnings("error")
Turn warnings into exceptions
warnings.resetwarnings()
Reset to the default handling of warnings

Example:

import warnings
...
...
warnings.simplefilter(action='ignore', category=UserWarning)
<code that throws warning>
warnings.resetwarnings()

This way the warning settings are restored after the known one has been passed