5. Conditionals and Loops

A) if Statement

The if statement for Python will seem amazingly familiar. It is made up of three main components: the keyword itself, an expression that is tested for its truth value, and a code suite to execute if the expression evaluates to nonzero or true.

The syntax for an if statement is:

if expression:
    expr_true_suite

The suite of the if clause, expr_true_suite, will be executed only if the above conditional expression results in a Boolean true value. Otherwise, execution resumes at the next statement following the suite.

A.1) Multiple Conditional Expressions

The Boolean operators and, or, and not can be used to provide multiple conditional expressions or perform negation of expressions in the same if statement.

if not warn and (system_load >= 10):
    print ("WARNING: losing resources")
    warn += 1

A.2) Single Statement Suites

If the suite of a compound statement, i.e., if clause, while or for loop, consists only of a single line, it may go on the same line as the header statement:

if make_hard_copy: send_data_to_printer()

Single line statements such as the above are valid syntax-wise; however, although it may be convenient, it may make your code more difficult to read, so we recommend you indent the suite on the next line. Another good reason is that if you must add another line to the suite, you have to move that line down anyway.

B) 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:
    expr_true_suite
else:
    expr_false_suite

Now we have the obligatory usage example:

if passwd == user.passwd:
    ret_str = "password accepted"
    id = user.id
    valid = True
else:
    ret_str = "invalid password entered... try again!"
    valid = False

C) elif (aka 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:
    expr1_true_suite
elif expression2:
    expr2_true_suite
        :
elif expressionN:
    exprN_true_suite
else:
    none_of_the_above_suite

Proxy for switch/case Statement?

At some time in the future, Python may support the switch or case statement, but you can simulate it with various Python constructs. But even a good number of if-elif statements are not that difficult to read in Python:

if user.cmd == 'create':
    action = "create item"
elif user.cmd == 'delete':
    action = 'delete item'
elif user.cmd == 'update':
    action = 'update item'
else:
    action = 'invalid choice... try again!'

Although the above statements do work, you can simplify them with a sequence and the membership operator:

if user.cmd in ('create', 'delete', 'update'):
    action = '%s item' % user.cmd
else:
    action = 'invalid choice... try again!'

We can create an even more elegant solution using Python dictionaries

msgs = {'create': 'create item', 'delete': 'delete item', 'update': 'update item'}
default = 'invalid choice... try again!'
action = msgs.get(user.cmd, default)

One well-known benefit of using mapping types such as dictionaries is that the searching is very fast compared to a sequential lookup as in the above if-elif-else statements or using a for loop, both of which have to scan the elements one at a time.

D) while Statement

Python’s while is the first looping statement we will look at. 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.

while expression:
    suite_to_repeat

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.

D.1) Counting Loops

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

The suite here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then bumped up by 1. 

D.2) Infinite Loops

One must use caution when using while loops because of the possibility that the 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 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 True:
    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 True is not going to somehow change to False. The main point of this server code is to sit and wait for clients to connect. 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. 

E) for Statement

The other looping mechanism in Python comes to us in the form of the for statement. It represents the single most powerful looping construct in Python. It can loop over sequence members, it is used in list comprehensions and generator expressions, and it knows how to call an iterator’s next() method and gracefully ends by catching StopIteration exceptions. If you are new to Python, we will tell you now that you will be using for statements a lot.

The for loop traverses through individual elements of an iterable (like a sequence or iterator) and terminates when all the items are exhausted. 

for iter_var in iterable:
    suite_to_repeat

With each loop, the iter_var iteration variable is set to the current elementof the iterable (sequence, iterator, or object that supports iteration), presumably for use in suite_to_repeat.

F) 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
        break
    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')
        deleteFromPhoneDB(phone2remove)    
        break

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.

G) continue Statement

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 before the next iteration of the loop can begin. Otherwise, the loop will terminate normally.

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

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 False, which presumably will result in appropriate action being taken soon after.