Flow-control structures: Difference between revisions

Content added Content deleted
m (→‎goto: Clarified comments)
(→‎{{header|Python}}: introduced an explicit header structure)
Line 337: Line 337:


=={{header|Python}}==
=={{header|Python}}==
===Exceptions===
<pre>
<pre>
# Flow Control Structures in Python (Exceptions)
# Flow Control Structures in Python (Exceptions)
Line 346: Line 347:


def main():
def main():
</pre>
# ***** Case 1 - Try, Except ***** #
====Case 1 - Try, Except====
<pre>
try:
try:
temp = 0/0
temp = 0/0
Line 353: Line 356:
print "An error occurred."
print "An error occurred."
# Output : "An error occurred"
# Output : "An error occurred"
</pre>
# ***** Case 2 - Try, Except ***** #
====Case 2 - Try, Except====
<pre>
try:
try:
temp = 0/0
temp = 0/0
Line 361: Line 365:
print "You've divided by zero!"
print "You've divided by zero!"
# Output : "You've divided by zero!"
# Output : "You've divided by zero!"
</pre>
# ***** Case 3 - Try, Except, Finally ***** #
====Case 3 - Try, Except, Finally====
<pre>
try:
try:
temp = 0/0
temp = 0/0
Line 374: Line 379:
# An error occurred
# An error occurred
# End of 'try' block...
# End of 'try' block...
</pre>
# ***** Case 4 - Try, Except within a function ***** #
====Case 4 - Try, Except within a function====
<pre>
def divisionbyzero(): # create a function that is sure to fail
def divisionbyzero(): # create a function that is sure to fail
temp = 0/0
temp = 0/0
Line 384: Line 390:
# Output :
# Output :
# You've divided by zero!
# You've divided by zero!
</pre>
# ***** Case 5 - Try, Except, Else ***** #
====Case 5 - Try, Except, Else====
<pre>
try:
try:
temp = 1/1 # not a division by zero error
temp = 1/1 # not a division by zero error
Line 395: Line 402:
# Output :
# Output :
# No apparent error occurred.
# No apparent error occurred.
</pre>
# ***** Case 6 - Try, Except, break, continue ***** #
====Case 6 - Try, Except, break, continue====
<pre>
i = 0
i = 0
while 1: # infinite loop
while 1: # infinite loop
Line 417: Line 425:
# You've divided by zero. Decrementing i and continuing...
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop
# Imaginary Number! Breaking out of loop
</pre>
# ***** Case 7 - Creating your own custom exceptions, raise ***** #
====Case 7 - Creating your own custom exceptions, raise====
<pre>
# Let's call our custom error "StupidError"; it inherits from the Exception class
# Let's call our custom error "StupidError"; it inherits from the Exception class
Line 436: Line 445:
# Output :
# Output :
# Something stupid occurred: Segfault
# Something stupid occurred: Segfault
</pre>
# ***** Case 8 - continue ***** #
====Case 8 - continue====
<pre>
i = 101
i = 101
for i in range(0,4): # loop 4 times
for i in range(0,4): # loop 4 times