pass Statement

One Python statement not found in C is the pass statement. Because Python does not use curly braces to delimit blocks of code, there are places where code is syntactically required. We do not have the equivalent empty braces or single semicolon the way C has to indicate “do nothing.” If you use a Python statement that expects a sub-block of code or suite, and one is not present, you will get a syntax error condition. For this reason, we have pass, a statement that does absolutely nothing—it is a true NOP, to steal the “No OPeration” assembly code jargon. Style- and development-wise, pass is also useful in places where your code will eventually go, but has not been written yet


def foo_func():


if user_choice == 'do_calc':

continue Statement

Whether in Python, C, Java, or any other structured language which features the continue statement, there is a misconception among some beginning programmers that the traditional continue statement “immediately starts the next iteration of a loop.” While this may seem to be the apparent action, we would like to clarify this somewhat invalid supposition. Rather than beginning the next iteration of the loop when a continue statement is encountered, a continue statement terminates or discards the remaining statements in the current loop iteration and goes back to the top.
If we are in a conditional loop, the conditional expression is checked for validity before beginning the next iteration of the loop. Once confirmed, then the next iteration begins. Likewise, if the loop were iterative, a determination must be made as to whether there are any more arguments to iterate over. Only when that validation has completed successfully can we begin the next iteration.
The continue statement in Python is not unlike the traditional continue found in other high-level languages. The continue statement can be used in both while and for loops. The while loop is conditional, and the for loop is iterative, so using continue is subject to the same requirements (as highlighted in the Core Note above) before the next iteration of the loop can begin. Otherwise, the loop will terminate normally.


valid = 0
count = 3
while count > 0:
    input = raw_input("enter password")
    # check for valid passwd
    for eachPasswd in passwdList:
        if input == eachPasswd:
            valid = 1
        if not valid: # (or valid == 0)
            print "invalid input"
            count = count - 1

In this combined example using while, for, if, break, and continue, we are looking at validating user input. The user is given three opportunities to enter the correct password; otherwise, the valid variable remains a false value of 0, which presumably will result in appropriate action being taken soon after.

break Statement

The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. The most common use for break is when some external condition is triggered (usually by testing with an if statement), requiring a hasty exit from a loop. The break statement can be used in both while and for loops.


count = num / 2
while count > 0:
    if (num % count == 0):
        print count, 'is the largest factor of', num
    count = count - 1

The task of this piece of code is to find the largest divisor of a given number num. We iterate through all possible numbers that could possibly be factors of num, using the count variable and decrementing for every value that does NOT divide num. The first number that evenly divides num is the largest factor, and once that number is found, we no longer need to continue and use break to terminate the loop.


phone2remove = '555-1212'
for eachPhone in phoneList:
    if eachPhone == phone2remove:
        print "found", phone2remove, '… deleting'

The break statement here is used to interrupt the iteration of the list. The goal is to find a target element in the list, and, if found, to remove it from the database and break out of the loop.

range() function

The built-in function range() can turn your foreach-like for-loop back into one that you are more familiar with, i.e., counting from zero to ten, or counting from 10 to 100 in increments of 5.

range() Full Syntax

Python presents two different ways to use range(). The full syntax requires that two or all three integer arguments are present:
range( start, end, step=1)
range() will then return a list where for any k, start <= k < end and k iterates from start to end in increments of step. step cannot be 0, or else an error condition will occur.

>>> range(2,19,3)
[2, 5, 8, 11, 14, 17]

If step is omitted and only two arguments given, step takes a default value of 1.

>>> range(3,7)
[3, 4, 5, 6]

Let’s take a look at an example used in the interpreter environment:

>>> for eachVal in range(2,19,3):
	print "value is ",eachVal

value is  2
value is  5
value is  8
value is  11
value is  14
value is  17

range() Abbreviated Syntax

range() also has a simple format, which takes one or both integer arguments:
range( start=0, end)
Given both values, this shortened version of range() is exactly the same as the long version of range() taking two parameters with step defaulting to 1. However, if given only a single value, start defaults to zero, and range() returns a list of numbers from zero up to the argument end:

>>> range(5)
[0, 1, 2, 3, 4]

We will now take this to the Python interpreter and plug in for and print statements to arrive at:

>>> for python in range(5):
	print python

Switch/Case Statement Proxy

Earlier in previous programs, we introduced the if-elif-else construct and indicated that Python did not support a switch/case statement. In many cases, an incredibly long set of if-elif-else statements can be replaced by a for loop, which contains the “case” items in a sequence which is iterated over. Consider the following alternative approach for switch :


>>> for amd in ('add','delete','quit'):
    if cmd== user.cmd:
        action = amd + "item"
        valid = 1
        action = "invalid choice"
        valid = 0

You are now probably glad to see that there is some kind of substitute for the lack of a switch/case statement in Python, but do you realize that using a list gives you even more power as a programmer? In other languages, the elements of a case statement are constant and a static part of the code. By using lists in Python, not only can these elements be variables, but they can also be dynamic and changed during run-time!
Final note, it may have surprised you to see an else statement at the end there.Yes, else statements can be used with for loops. In this case, the else clause is executed only if the for loop finished to completion.

for Statement

The other looping mechanism in Python comes to us in the form of the for statement. Unlike the traditional conditional looping for statement found in mainstream third generation languages (3GLs) like C, Fortran, or Pascal, Python’s for is more akin to a
scripting language’s iterative foreach loop.

General Syntax

Iterative loops index through individual elements of a set and terminate when all the items are exhausted. Python’s for statement iterates only through sequences, as indicated in the general syntax here:


for items in sequence:


>>> nameList = ['Walter', "Nicole", 'Steven', 'Henry']
>>> for eachName in nameList:
	print eachName


Infinite Loops

One must use caution when using while loops because of the possibility that this condition never resolves to a false value. In such cases, we would have a loop that never ends on our hands. These “infinite” loops are not necessarily bad things… many communications “servers” that are part of client-server systems work exactly in that fashion. It all depends on whether or not the loop was meant to run forever, and if not, whether the loop has the possibility of terminating; in other words, will the expression ever be able to evaluate to false?


while 1:
    handle, indata = wait_for_client_connect()
    outdata = process_request(indata)
    ack_result_to_client(handle, outdata)

For example, the piece of code above was set deliberately to never end because the value 1 will never evaluate to Boolean false. The main point of this server code is to sit and wait for clients to connect, presumably over a network link. These clients send requests which the server understands and processes. After the request has been serviced, a return value or data is returned to the client who may either drop the connection altogether or send another request. As far as the server is concerned, it has performed its duty to this one client and returns to the top of the loop to wait for the next client to come along.

while Statement

Python’s while is the first looping statement. In fact, it is a conditional looping statement. In comparison with an if statement where a true expression will result in a single execution of the if clause suite, the suite in a while clause will be executed continuously in a loop until that condition is no longer satisfied.

General Syntax

while expression:

The suite_to_repeat clause of the while loop will be executed continuously in a loop until expression evaluates to Boolean false. This type of looping mechanism is often used in a counting situation, such as the example in the next subsection.

>>> count = 0
>>> while (count <9):
	print "the index is :",count
	count = count + 1

the index is : 0
the index is : 1
the index is : 2
the index is : 3
the index is : 4
the index is : 5
the index is : 6
the index is : 7
the index is : 8

elif (a.k.a. else-if) Statement

elif is the Python else-if statement. It allows one to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true. Like the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.


if expression1:
elif expression2:
elif expressionN:

At this time, Python does not currently support switch or case statements as in other languages. Python syntax does not present roadblocks to readability in the presence of a good number of if-elif statements.


if (user.cmd == 'create'):
    action = "create item"
    valid = 1
elif (user.cmd == 'delete'):
    action = 'delete item'
    valid = 1
elif (user.cmd == 'quit'):
    action = 'quit item'
    valid = 1
    action = "invalid choice… try again!"
    valid = 0

Python presents an elegant alternative to the switch/case statement in the for statement. Using for, one can “simulate” switches by cycling through each potential “case,” and take action when warranted.

if else Statement

Like other languages, Python features an else statement that can be paired with an if statement. The else statement identifies a block of code to be executed if the conditional expression of the if statement resolves to a false Boolean value. The syntax is what you expect:

if expression:

Now the obligatory usage example:

>>> username = "john"
>>> password = "123"
>>> if username == "john" and password =="123":
    print "Hello john"
    print "welcome to python"
    print "access denied"

Hello john
welcome to python
>>> if username == "john1" and password =="123":
    print "Hello john"
    print "welcome to python"
    print "access denied"

access denied