Break/Continue/Pass/Try and Except/Raise

Consider

$ cat test
#!/usr/bin/python
a=0
b=10
while (a < 10):
a = a + 1
print a

./test
1
2
3
4
5
6
7
8
9
10

Break

will break out of the loop when the condition is met

#!/usr/bin/python
a=0
b=10
while (a < 10):
a = a + 1
if (a == 5):
break
print a

$ ./test
1
2
3
4

Continue

rejects all the remaining statements in the current iteration and moves control to the top of the loop (if condition hit and you don't want it to carry out an action)

$ cat test
#!/usr/bin/python
a=0
b=10
while (a < 10):
a = a + 1
if (a == 5):
continue
print a

$ ./test
1
2
3
4
6
7
8
9
10

Pass

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet

$ cat test
#!/usr/bin/python
a=0
b=10
while (a < 10):
a = a + 1
if (a == 5):
pass
print a

$ ./test
1
2
3
4
5
6
7
8
9
10

Try and except

If an error is encountered, a try block code execution is stopped and transferred down to the except block.

$ cat try
#!/usr/bin/python
try:
x= 5 + "today"
except:
print "darn it"

$ ./try
darn it

it is particular useful in this kind of issue:

$ cat try1
#!/usr/bin/python
z = 5
x = 0

try:
y = z/x
except ZeroDivisionError:
print "Zero division error detected"

[pdw@centos6gui selfstudy]$ ./try1
Zero division error detected

 

 

Raise

The raise statement allows the programmer to force a specified exception to occur

$ cat raise
#!/usr/bin/python
raise TypeError ("hi")

[pdw@centos6gui selfstudy]$ ./raise
Traceback (most recent call last):
File "./raise", line 2, in <module>
raise TypeError ("hi")
TypeError: hi