BeginnersTutorial:Tutorial/Lesson 5

From jWork.ORG
Jump to: navigation, search

Lesson 5: Conditions

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

A piece of code can be executed if 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'

Leading whitespace (spaces and tabs) at the beginning of a logical line are important. They are used to compute the indentation level of the line in order to determine the grouping of statements.

Boolean operators are used to manipulate TRUE or FALSE values. These operators have the following meanings:

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 (a shortcut of "else if")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 "if previous condition fails, do something if"

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

Here 4>70 is FALSE, so the code checks the condition 4<7. The latter is true, so the program prints the line "This is normal.."