Logical statements

From GeoMod

Jump to: navigation, search

We have already seen the use of logical statements in the bouncing ball model, now we will look at them in a little more detail.

First we'll create a little program that spits out a series of numbers;

for i in range(10):
    print i

which prints out;

0
1
2
3
4
5
6
7
8
9

Contents

if

Now we will insert a basic logical if statement to print out only the numbers greater than 5.

for i in range(10):
    if i > 5:
        print i

which gives;

6
7
8
9

Just like in the for loop the statements in the if statement need to be indented for the program to know that you are in the statement.

The logical statement if i > 5: can be read as;

if i is greater than 5 then print i

Logical operators

The > sign is a logical operator, the others you can use are;

Operator meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to

for example, the program;

for i in range(10):
    if i >= 5:
        print i

gives,

5
6
7
8
9

while;

for i in range(10):
    if i <= 5:
        print i

gives;

0
1
2
3
4
5

Combining logical statements with "and"

We can combine logical statements using the keyword "and", like this;

for i in range(10):
    if i > 5 and i < 8:
        print i

to give;

6
7

Playing opposites with "not"

Also we can produce the opposite of a logical statement by adding "not" to the front like this;

for i in range(10):
    if not (i > 5):
        print i

which gives;

0
1
2
3
4
5

else

The else statement is only used as part of a logical statement to tell the program what to do if the initial logical statement does not apply. For example, say we want to print out "hi" every time the above if statement is not true, and the numbers if it is true, we will use something like this;

for i in range(10):
    if i > 5:
        print i
    else:
        print "hi"

which gives;

hi
hi
hi
hi
hi
hi
6
7
8
9

This if - else statement can be read

if i is greater than 5 then print the value of i, otherwise (else) print "hi"
Personal tools