Conditional Statements


Conditional statements are ones that are executed only if some condition is true. Here's an example:

x = 5

if x<6:
print 'x is less than 6'   

Here's a more general specification for the syntax of an  'if' statement:

if <condition>:
<statement>
 
The <...> syntax means we're defining the form of something, not an example.  It comes from a method of specifying languages called Backus-Naur form (BNF). We'll use this type of specification often to describe languages.

An else clause says what to do if the 'if' condition is false, e.g.,

if x<6:

print 'less than 6'
else:
print 'more or equal to 6'

If you have more than two alternatives, use the keyword elif, which is short for else-if.

if x<6:

print 'less than 6'
elif x<10:
print 'between 6 and 10'
else:
print 'ten or bigger'

You can have as many 'elif's as you want.

Comparison and Logical Operators

Here are examples of the comparison operators that you can use in conditionals:

x < 3

x > 3
x == 3
x != 3
x <= 3
x >= 3

Note that == is used for equality comparison as opposed to = (the assignment operator). This causes a lot of errors even for experienced programmers. != means not equal.

You can also use the logical operators and, or, and not, to create more complex conditions, e.g.,

if (x<3 and y != 7):

Statement Blocks

Often, in a conditional statement, you want more than one thing to occur. Programming languages allow you to define a statement block, which is one or more statements that are grouped together. In many languages, such as C, C++, and Java, curly braces are used to denote statement blocks:

if <condition>
{

<statement>
<statement>
 ... 
}

In such languages, indentation is ignored by the compiler. Python is different. It uses indentation to define where a block begins and ends and doesn't use curly brackets. Tabs are used to indent:

if <condition> :
<statement>  
<statement>
... 


Can you figure out the value of x following the following snippet:

x=5

if x<4:
x=x+1
x=x+1

What if x began as 3?


Recent site activity