If and while statements

By 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.

See also

Sign up to the Creative Coding Newletter

Join my newsletter to receive occasional emails when new content is added, using the form below:

Popular tags

555 timer abstract data type abstraction addition algorithm and gate array ascii ascii85 base32 base64 battery binary binary encoding binary search bit block cipher block padding byte canvas colour coming soon computer music condition cryptographic attacks cryptography decomposition decryption deduplication dictionary attack encryption file server flash memory hard drive hashing hexadecimal hmac html image insertion sort ip address key derivation lamp linear search list mac mac address mesh network message authentication code music nand gate network storage none nor gate not gate op-amp or gate pixel private key python quantisation queue raid ram relational operator resources rgb rom search sort sound synthesis ssd star network supercollider svg switch symmetric encryption truth table turtle graphics yenc