You are a guest. Restricted access. Read more


Conditionals are where a section of code is only run if certain conditions are met. The most common conditional is the 'if' statement.

One other point is that the code to be executed if the conditions are met. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but python requires that you do it. Here is an example of both of the above points:

Here is how it works:

if (conditions to be met):
    {do this}
    {and do this}
{but this happens regardless because it is not indented}

Here is an example:

y = 10
if y == 10:
    print 'y is equal to  10'

Table 1 - Boolean operators

Expression Function
< less than
<= less that or equal to
> greater than
>= greater than or equal to
!= not equal to
<> not equal to (alternate)
== equal to

Use else and elif to deal with situations where your boolean expression ends up FALSE:

a = 1
if a > 5:
    print 'This is wrong answer'
    print 'Yes, Correct answer a=',a

elif is just a shortened way of saying else if.

z = 4
if z > 70:
    print 'Something is wrong, z is too large'
elif z < 7:
    print 'This is normal, z=',z

python/conditions.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0