CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests

if statement

The if statement allows you to tell the computer to do some code only if something is true. Here is an example.

y = 10
if x > 10:
    y = x

This little snippet first sets y to 10; but if x is more than that, then it copies that larger value into y. (By the way, “y = max(10x)” would accomplish the same thing.)

Here is the general template for an if statement.

if condition:

Like the for statement, the body can include multiple statements. The important thing is that each line of the body be indented the same distance. When Python reaches a line that lines up with the i in if, it knows that the body is over, and it's reached code that it should do even if the condition is false.

What can go in the condition? We'll see some other options later, but for now we'll stick to the comparison operators that allow you to compare numbers (or strings).

<less than (<)
>greater than (>)
<=less than or equal (≤)
>=greater than or equal (≥)
!=not equal (≠)
==equal (=)

The first four are relatively obvious. Inequality, oddly, uses an exclamation point to suggest the word not But most importantly, equality testing is done using two equal signs! Using two here is required; Python allows the single-equal only for assignment in assignment statements.

Here is a more complex example.

num_zero = 0
for i in range(10):
    user_num = int(input())
    if user_num == 0:
        print('found a zero')
        num_zero = num_zero + 1
print('found ' + str(num_zero) + ' zeroes')

This for loop iterates 10 times. Each time, it reads one number from the user, then tests whether that number matches 0 (note the double-equal!). When it finds one, it displays a message to that effect before making num_zero go up by one. Then it starts the loop the next time. You know the final print happens only after the loop is complete since the p lines up beneath the f in for.