• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Conditions

Your programs can make decisions. No, they can't tell you which laundry detergent to buy. But they can take pieces of information, compare them, and then perform different tasks depending on the outcome.

For instance, suppose that you want to check the name a user provides and make sure that the user gives a name at least three characters long.

The decision that the program needs to make is based on this one fact. If the user's name is three characters long or longer, the program does one thing; if the user's name is less than three characters long, the program does something else.

There are actually two parts to this decision. The first part is to test to see whether the condition is met. If the name is three characters long, the condition is met, or we say that it is true. Otherwise, the condition is not met, or it is false. All conditions are either true or false.

A value that is either true or false is called a boolean value.


The second part of the decision-making process is to choose which piece of code to execute based on the true/false condition. Sometimes, there is only one option: Some code is executed if the condition is true. If the condition is false, no code is executed at all. Sometimes, there is an alternate set of code to execute if the condition is false.

Get used to phrasing questions and comparisons as conditions. Computers always think in terms of true and false, not in abstract terms such as “what does this mean?”

For instance, if you want the computer to perform three different tasks based on whether a variable is 1, 2, or 3, you might phrase it like this:

  • Is the variable's contents equal to 1? If so, then do this…

  • Is the variable's contents equal to 2? If so, then do this…

  • Is the variable's contents equal to 3? If so, then do this…

So instead of asking the computer something complex such as “do one of these things based on the value of the variable,” you ask it three separate questions that have true or false results.

Conditions are almost always based on a comparison. You can compare the values of two variables to see whether they are equal. You can also compare them to see whether one is less than the other or greater than the other. If the variables are strings, you can compare them to see whether one appears alphabetically before or after the other.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint