Tutorial:Jython/7 Conditions

From HandWiki

Conditions

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:

<jc lang="python"> y = 10 if y == 10:

   print 'y is equal to  10'

</jc>

<html> 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

</html>

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

<jc lang="python"> a = 1 if a > 5:

   print 'This is wrong answer'

else:

   print 'Yes, Correct answer a=',a

</jc>

elif is just a shortened way of saying else if.

<jc lang="python"> z = 4 if z > 70:

   print 'Something is wrong, z is too large'

elif z < 7:

   print 'This is normal, z=',z

</jc>