If and while statements


Martin McBride, 2017-01-16
Tags condition relational operator if statement while statement
Categories logic programming logic

Almost every programming language has if statements and while loops, or some kind of equivalent. These are the basic ways a program can make decisions - how it can decide to do one thing rather than another, or how it can decide to do the same thing as many times as it needs to.

This is called programming logic, and while a lot of it is common sense, there are still a few tips and tricks which can make things easier.

If statements

Here is an if statement, in Python, although you could produce similar code many other languages.

x = 3
if x < 10:
    print('x is small')

The code is quite simple. The if statement tests the value of x to see if it is less than 10, and if it is, it prints the line of text 'x is small'. In this case, since x is 3, the text will be printed. I x was, say, 11, them nothing would be printed.

While loops

Here is a while loop, again in Python:

x = 0
while x < 10:
    print(x)
    x = x + 1

In this case, x starts at 0, and while ever x is less than 10, the body of the loop executes. The loop prints the current value of x, then adds 1 to x. The program prints 0, 1, 2 ...

When x reaches 10, the condition of the while loop is no longer true - x is no longer less than 10. The loop ends, and the program continues on past the loop code.

Conditionals

The rest of this section isn't really about if and while, it is about the conditional statements that they make use of. Knowing how to create and simplify these statements is a useful skill in computational thinking.

Copyright (c) Axlesoft Ltd 2021