Jump to content

Flow-control structures: Difference between revisions

no edit summary
No edit summary
Line 1:
[[Category:Less Than 20 Examples]]{{Task|Control Structures}}
{{Control Structures}}
In this task, we document common flow-control structures. One common example of a flow-control structure is the <codett>goto</codett> construct. Note that [[Conditional Structures]] and [[Loop Structures]] have their own articles.
 
=={{header|Ada}}==
Line 311:
===Loops===
Python supports ''break'' and ''continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
<lang python>
# Search for an odd factor of a using brute force:
for i in range(n):
Line 322:
result = None
print "No odd factors found"
</pythonlang>
In addition, as shown in the foregoing example, Python loops support an ''else:'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target. In that situation the ''else:'' suite can be used to handle the failure. (In most other languages one is forced to use a "sentinel value" or a special flag variable ... typically set to "False" before the loop and conditionally set to "True" within the loop to handle situations for which the Python ''else:'' on loops is intended).
 
Line 335:
A custom Exception class is normally declared with the ''pass'' statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:
 
<lang python>
class MyException(Exception): pass
</pythonlang>
 
One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.
Line 345:
To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:
 
<lang python>
class MyVirtual(object):
def __init__(self):
raise NotImplementedError
</pythonlang>
 
It then becomes necessary for any descendants of this class to over-ride the ''__init__()'' method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.
 
====Case 1 - Try, Except====
<lang python>
try:
temp = 0/0
Line 361:
print "An error occurred."
# Output : "An error occurred"
</pythonlang>
====Case 2 - Try, Except====
<lang python>
try:
temp = 0/0
Line 370:
print "You've divided by zero!"
# Output : "You've divided by zero!"
</pythonlang>
====Case 3 - Try, Except, Finally====
<lang python>
try:
temp = 0/0
Line 384:
# An error occurred
# End of 'try' block...
</pythonlang>
 
Note: Prior to version 2.5 a ''try:'' statement could contain either series of ''except:'' clauses '''or''' a ''finally:'' clause but '''not both.''' It was thus necessary to nest the exception handling in an enclosing ''try:''...''finally:'' loop like so:
 
<lang python>
try:
try:
Line 397:
finally:
do_some_cleanup() # run in any case, whether any exceptions were thrown or not
</pythonlang>
====Case 4 - Try, Except, Else====
<lang python>
try:
temp = 1/1 # not a division by zero error
Line 409:
# Output :
# No apparent error occurred.
</pythonlang>
====Case 5 - Try, Except, break, continue====
<lang python>
i = 0
while 1: # infinite loop
Line 432:
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop
</pythonlang>
====Case 6 - Creating your own custom exceptions, raise====
<lang python>
# Let's call our custom error "StupidError"; it inherits from the Exception class
Line 448:
# Output :
# Something stupid occurred: Segfault
</pythonlang>
 
===Case 7 - continue, else in "for" loop===
<lang python>
i = 101
for i in range(4): # loop 4 times
Line 472:
if(__name__ == "__main__"):
main()
</pythonlang>
 
===The "with" statement===
Line 478:
See [[http://www.python.org/peps/pep-0343.html PEP 0343, The "with" statement]]
 
<lang python>
class Quitting(Exception): pass
max = 10
Line 488:
raise Quitting
print line,
</pythonlang>
 
The ''with'' statement allows classes to encapsulate "final" (clean-up) code which will automatically be executed regardless of exceptions that occur when working "with" these objects. Thus, for the foregoing example, the file will be closed regardless of whether it's more than 10 lines long. Many built-in and standard library classes have "context managers" which facilitate their use in ''with:'' code. In addition it's possible to define special __enter__() and __exit__() methods in one's own classes which will be implicitly called by the interpreter when an object is used within a ''with:'' statement.
Cookies help us deliver our services. By using our services, you agree to our use of cookies.