Make If- and Switch Statements |
Make If- and Switch Statements Many times you would like the value of an attribute to depend on whether something is or is not true of another attribute. That's when you use an if-statement. If you have more than two possibilities, use a switch statement. An if-statement has three parts: the condition, the value when the condition is true, and the value when the condition is false. To create an if-statement,
Or,
You can create nested if-statements by using if-statements as values for if-statements. Switch statements are very helpful for recoding data. Switch statements, unlike if-statements, can deal with more than two possibilities. There are three parts to a switch statement: the value to switch on, the test values, and the result values. Usually you will write switch statements similar to the one shown here. Your value to switch on will be the name of an attribute, the test values will be values that the attribute takes on, and the result values will amount to a recoding of the original attribute. TinkerPlots returns the result value whose test value matches the value being switched on. A switch statement's tests are not limited to equality. In the statement below, for example, TinkerPlots first compares the value of N with 0 and returns "zero" if N does equal 0. If not, it tests to see whether N is less than 5 and returns "low" if it is. If not, it goes on to compare N with 10 and returns "medium" if N is less than 10. If no test has succeeded thus far, it returns "high." Here are the rules to keep in mind when writing switch statements. •If you do not explicitly specify a comparison operator, TinkerPlots will test for equality. •TinkerPlots returns the first result value whose test returns true. The fact that later tests might also return true has no effect on the result. •A switch value can itself be an expression, not just the name of an attribute, for example, . The result of evaluating the expression is used in the test. •Result values may be any expression (including if- or switch statements). •The switch value is substituted for any question marks or missing arguments to functions that appear in the test expression.
|