Python conditionals

Conditionals

While the keywords are slightly different, Python supports the idea of an if statement, a sequence of else if's, and a final else statement.

The comparison operators themselves are similar to C, for example:

if (x == w):
	print "x == w"
elif (x < y):
	print "x < y"
elif (x < z):
	print "x < z"
else:
	print "x > all"

Iteration

Python supports a number of forms of iteration, again using indentation to identify blocks.

While loops are supported for basic iteration,
for loops are supported for iterating over the contents of a set or list,
(a range function will generate a set of numbers if you want a for loop to iterate over them)

Break and continue statements operate similarly to C.

Some examples:

# loop through values 1 to 5
x = 1
y = 5
while (x < y):
	print "next iteration, x is ", x
        x = x + 1

# print the contents of mylist
mylist = ['foo', 3, 1.0]
print "mylist contents = ["
for i in mylist
	print i, ","
print "]"

# print numbers 3..8
for i in range(3, 8):
	print i

Pass statement

Python includes a pass statement, which does nothing but is handy when the syntax of the language requires a statement somewhere where you want to do nothing, e.g.

# infinite loop doing nothing
while True:
	pass