CHAPTER 5

image

Conditional Statements

Conditional statements are an important part of many programs. They allow logic control of our programs. There are three main conditional statement types in Python. If / Elif / Else conditionals, For loops and While loops.

IF / ELIF / ELSE Statements

The if statements allow us to check the truth of a statement or statements and apply logic to the various possibilities. The if statement is simple at its heart.

if (statement) :
    # do the following code
    # do this line as well
# This line is NOT part of the if statement.

The statement starts with the 'if' keyword (the 'if' must be in lowercase) followed by the conditional expression then a colon character. The line(s) of code that you want to have executed if the statement is true, must be indented.

Assume that the variable a = 3 and the variable b = 7.

if a < b:
    print("a less than b")

a less than b

You can also add a second option so that if the first statement is not true, the program would run the alternate code. This is the else option. The ‘else’ phrase does not allow for any additional logic and must be followed by a colon.

if b < a:
    print("b less than a")
else:
    print("a less than b")

a less than b

If you have more than two options, you can use the elif option of the if / else statement. You can have as many elif statements as you need. The elif option must have some sort of logic and be followed by a colon.

if a == 3:
    print('a=3')
elif a == 4:
    print('a=4')
else:
    print('a not 3 or 4')

a=4

The if / elif / else statements must be at the main indention level with the logic indented.

a = 3
b = 4
c = 6
if a<b:
    d = 5
if (c<b) or (b<a):
    d = 2
    e = 5
elif (c<a):
    c = a
    a = 7
print a,b,c,d,e
7 4 6 5 5

For

The for keyword creates a loop controlled by the parameters that follow the assignment and will run a given number of times. Like the if statement, the keyword is followed by a sequence that will be “stepped” through (iteration), followed by a colon. All logic that is to be done within the loop is indented. In its simplest form, the for loop looks like this:

for x in range(3):
    print(x)

0
1
2

The range function will create a list based on the numbers that are in the parameter. In the earlier case, the list would be [0,1,2]. Under Python 2.x, you can use the xrange function instead of range. Xrange creates a generator that, in turn, creates the numbers as needed instead of creating a list, using less memory and makes the loop faster, because the numbers are generated as needed. If you are using Python 3.x, the xrange function is removed but is actually renamed as range.

for x in xrange(3):
    print(x)

0
1
2

As I stated earlier, the range function will create a list of values based on the parameter values. Because of this, you can use a list directly in your for statement.

for x in [1,2,3,4,5,6,7,8,9,10]:
    print x

1
2
3
4
5
6
7
8
9
10

You can also walk, or iterate, through a string as the list of values.

for char in "The time has come":
    print char
T
h
e

t
i
m
e

h
a
s

c
o
m
e

If you are iterating through a dictionary, you can the .iteritems() method of the dictionary object.

d = {'Key1':1,'Key2':2,'Key3':3}
for key,value in d.iteritems():
    print key,value

Key3 3
Key2 2
Key1 1

Another helpful option is to use the enumerate() function. This will allow you to iterate through a list and the count as well as the list value will be returned as a tuple.

mounts = ['Evans','Grays Peak','Longs Peak','Quandary']
for m in enumerate(mounts):
    print m

(0, 'Evans')
(1, 'Grays Peak')
(2, 'Longs Peak')
(3, 'Quandary')

Break

The break statement allows early termination of a loop (for or while). In this snippet, the for loop should run from 0 to 4, but when the loop hits the value of 3, the loop is terminated.

for x in range(5):
    if x == 3:
        break
    else:
        print(x)

0
1
2

Continue

The continue optional statement in a for loop allows for normal loop operation, but at the specified condition, the rest of the logic will be skipped for that iteration. In the snippet here, when the value in the for loop reaches 3, the print(x) logic will be skipped and the loop continues.

for x in range(5):
    if x == 3:
        continue
    else:
        print(x)

0
1
2
4

Else

The for loop also supports an optional else statement. Unlike the else statement used with the if conditional, it is more like the else in a try statement in that it always runs at the end of the loop.

for x in range(5):
    print x
else:
    print "The else"

0
1
2
3
4
The else

Pass

The pass statement will do nothing, which seems like a silly thing to have. However, it is actually valuable where you need to have a statement (like an option within an if clause) or to “stub” out a routine to be filled in later.

a = 3
if a == 2:
    pass
else:
    print("A != 2")

A != 2

def testfunction():
    pass

While

The while loop is used when you need your logic repeated until a certain condition is met, usually because you don't know how many times it will take. This could be because you are waiting for some condition to be met, like a timer expiring or a certain key press.

cntr = 0
while cntr < 11:
    print cntr
    cntr += 1
0
1
2
3
4
5
6
7
8
9
10

You can create an infinate loop as well, so you might want to be careful and create a way for the loop to break. If you end up in an infinate loop, you can press Ctrl + C to end the execution of your code.

cntr = 1
while cntr == 1:
    #do something forever.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset