
Branching that involves "if - else" allows your
program to behave very differently depending on what a user inputs. For
example, you could write a script that would act one way toward you and
a different way toward everyone else. Here's the basic form of an if -
then statement:
— OR —
— OR — Here's the basic form of an if - else statement:
The important parts of this structure are:
Remember, spacing is only there to make the script more legible. You can put the entire if - then statement on one line if you want, but that would be hard to read. Here's an example of an if-then statement in action. "if" statements have two parts. The first part evaluates whether a value is true or false and the second part of the statement contains the appropriate responses. We'll look first at the process of evaluating true and false.
You can use logical operators to create statements that "evaluate" to either true or Here's the basic form of an if - then statement. The following examples illustrate this:
As is often the case, the hardest part about learning to use logical operators is remembering what the symbols mean. In most cases, you'll find the basic ideas pretty intuitive as long as you can easily read and write the symbols.
The second component of the "if" statement is pretty simple. It's just one or more lines of code which will be executed only if the logical statement in the first part of the "if" statement evaluates to true. These lines of code are enclosed within curly brackets.
The following are several examples of "if" statements. As you'll see, the first word is always "if", and that is followed by a statement enclosed in parentheses. This statement in the parentheses either evaluates to true or false. If it evaluates to true, the actions enclosed in the curly brackets that follow it will be executed. If the statement in the parentheses evaluates to false, nothing will happen.
You can use the "else" statement immediately following an "if" statement if you want a set of commands to be executed in the event that the "if" statement evaluates to false. It looks like this:
— OR —
|