Jump to content

Flow-control structures: Difference between revisions

→‎{{header|Python}}: introduced an explicit header structure
m (→‎goto: Clarified comments)
(→‎{{header|Python}}: introduced an explicit header structure)
Line 337:
 
=={{header|Python}}==
===Exceptions===
<pre>
# Flow Control Structures in Python (Exceptions)
Line 346 ⟶ 347:
 
def main():
</pre>
# ***** ====Case 1 - Try, Except ***** #====
<pre>
try:
temp = 0/0
Line 353 ⟶ 356:
print "An error occurred."
# Output : "An error occurred"
</pre>
# ***** ====Case 2 - Try, Except ***** #====
<pre>
try:
temp = 0/0
Line 361 ⟶ 365:
print "You've divided by zero!"
# Output : "You've divided by zero!"
</pre>
# ***** ====Case 3 - Try, Except, Finally ***** #====
<pre>
try:
temp = 0/0
Line 374 ⟶ 379:
# An error occurred
# End of 'try' block...
</pre>
# ***** ====Case 4 - Try, Except within a function ***** #====
<pre>
def divisionbyzero(): # create a function that is sure to fail
temp = 0/0
Line 384 ⟶ 390:
# Output :
# You've divided by zero!
</pre>
# ***** ====Case 5 - Try, Except, Else ***** #====
<pre>
try:
temp = 1/1 # not a division by zero error
Line 395 ⟶ 402:
# Output :
# No apparent error occurred.
</pre>
# ***** ====Case 6 - Try, Except, break, continue ***** #====
<pre>
i = 0
while 1: # infinite loop
Line 417 ⟶ 425:
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop
</pre>
# ***** ====Case 7 - Creating your own custom exceptions, raise ***** #====
<pre>
# Let's call our custom error "StupidError"; it inherits from the Exception class
Line 436 ⟶ 445:
# Output :
# Something stupid occurred: Segfault
</pre>
# ***** ====Case 8 - continue ***** #====
<pre>
i = 101
for i in range(0,4): # loop 4 times
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.