Conditionals and recursion:
Conditional statements are based on booleans. A boolean expression is an expression that is either true or false. The
'==' operator compares two values and produces a boolean retult:
>>>5 == 5
True
>>>5 == 6
False
There are also:
x != y #x is not equal to y
x > y #x is greater than y
x < y #x is less than y
x >= y #x is greater than or equal to y
x <= y #x is less than or equal to y
Logical operators:
There are three logical operators: and, or, not.
x > 0 and x < 10 is true only if x is greater than 0 and less than 10
Conditional execution:
The simplest form of a conditional statement is:
if x > 0:
print "x is positive"
The boolean expression after the if statement is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens.
General form:
HEADER:
FIRST STATEMENT
...
LAST STATEMENT
Note: the header ends with a colon (:). The indented statements are called a block. A statement block inside a
compound statement is called the body of the statement.
Alternative execution:
A second form of the if statement is alternative execution, in which there are two possibilities and the condition
determines which one gets executed.
if x % 2 == 0:
print x, "is even"
else:
print x, "is odd"
The alternatives are called branches, because they are branches in the flow of execution.
Chained conditionals:
Sometimes there are more than two possibilities and more branches are needed.
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
Again exactly one branch will be executed. There is no limit of the number of elif statements but only a single
( optional ) else statement is allowed and must be the last branch in the statement.
Nested conditionals:
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
Author: Georgi Christov ( aka masterofpuppets )
e-mail: programming.unlimited@abv.bg