If statements are a basic part of every programming
language. The idea is that they allow you to test a condition and then perform an
action if the test passed.
This might sound like a very simple idea, but it’s a simple
idea that has a lot of very grand implications. If you think about it, every
single decision follows the same structure. If your sandwich is sitting in
front of you, you go through a series of checks to decide whether or not to eat
it, “If I am hungry, then I will eat the sandwich.” “If I like the sandwich
ingredients, then I will eat the sandwich.” (It’s good to stop at this point
and each the sandwich. Otherwise you may get lost in the process of figuring
out if you’ve done your if-then structure for every decision aspect you needed
to).
Let’s look at a really simple example and then we’ll look at
a more interesting example.
In this example we are testing if an integer i is equal to
0. If it is, we print out the fact that it is zero. Pretty simple, eh? As
promised, here’s a more interesting example.
In this example, we are using two methods not shown, one
validates that a user ID exists and the other validates that the password
entered for that ID is correct. If both of those return true, we give the user
access to the system.
Why should you care?
Have you ever played against a computer chess program and
felt like it was intelligent? Or seen a chat bot that for a second, seemed to
be really answering your questions? At some level those things and others are
powered by if statements. The ability to perform an action based on criteria is
the first step in taking a computer from being a machine with consistent input
and output to being a device that may seem to think and react to you. Not to
sound too grandiose, but it’s the first step into the magical world of
programming.
No comments:
Post a Comment