Page 157 - Learn To Program With Scratch
P. 157

The and Operator

                          The and operator takes two expressions as parameters. If both expressions
                          are true, the and operator returns true; otherwise, it returns false. The
                          truth table for and, which lists the output of the operator for all possible
                          combinations of inputs, is shown in Table 6-5.

                          Table 6-5: Truth Table for the and Operator

                          X                      Y
                          true                   true                  true
                          true                   false                 false
                          false                  true                  false
                          false                  false                 false


                          As an example of using the and operator, let’s say we’re creating a game in
                          which the player gets 200 bonus points when the score reaches 100 in the
                          first level. The game level is tracked by a variable named level, and the score
                          is tracked using a variable named score. Figure 6-12 shows how these condi-
                          tions can be tested using nested if blocks u or with the and operator v.









                                                                  
                          Figure 6-12: Checking multiple conditions using nested if blocks and the and operator

                             In both cases, the bonus points are added only when both condi-
                          tions are true. As you can see, the and operator provides a more concise
                          way for performing the same test. The command(s) inside the if block in
                          Figure 6-12 v will be executed only if level equals 1 and score equals 100. If
                          either condition is false, the entire test evaluates to false, and the change
                          score by 200 block will not be executed.

                          The or Operator
                          The or operator also takes two expressions as parameters. If either expres-
                          sion is true, the or operator returns true. It returns false only when the two
                          expressions are both false. The truth table for the or operator is given in
                          Table 6-6.







                                                                              Making Decisions   135

                                           www.it-ebooks.info
   152   153   154   155   156   157   158   159   160   161   162