19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1 ' AndDemo.sb<br />

2 TextWindow.Write("Game level: ")<br />

3 gameLevel = TextWindow.ReadNumber()<br />

4<br />

5 TextWindow.Write("Score.....: ")<br />

6 score = TextWindow.ReadNumber()<br />

7<br />

8 If ((gameLevel = 1) And (score > 100)) Then<br />

9 TextWindow.WriteLine("You get 200 bonus points!")<br />

10 EndIf<br />

Listing 9-3: The And opera<strong>to</strong>r<br />

The statement inside the If block (line 9) is run only if gameLevel equals<br />

1 and score is greater than 100. If either of these two conditions is false, the<br />

entire condition is found false and <strong>Small</strong> <strong>Basic</strong> won’t run the WriteLine()<br />

method on line 9.<br />

You can perform the same check by replacing lines 8–10 <strong>with</strong> the following<br />

nested If statements:<br />

If (gameLevel = 1) Then<br />

If (score > 100) Then<br />

TextWindow.WriteLine("You get 200 bonus points!")<br />

EndIf<br />

EndIf<br />

Do you see how the And opera<strong>to</strong>r is a more concise way <strong>to</strong> test multiple<br />

conditions? The nested If statements require five lines of code, but using<br />

And, you can do the same thing in only three lines of code!<br />

The Or Opera<strong>to</strong>r<br />

How do you like your pizza? You might want <strong>to</strong> eat pizza only if it has four<br />

kinds of meat or if the crust is gooey. When you have multiple conditions<br />

but only one condition needs <strong>to</strong> be true, the Or opera<strong>to</strong>r comes in<strong>to</strong> play.<br />

Take a look at the truth table for the Or opera<strong>to</strong>r in Table 9-3.<br />

Table 9-3: Truth Table for the Or Opera<strong>to</strong>r<br />

If X is If Y is Then (X Or Y) is<br />

"True" "True" "True"<br />

"True" "False" "True"<br />

"False" "True" "True"<br />

"False" "False" "False"<br />

If either of the two operands is true, or if they’re both true, the combined<br />

logical expression is true. The logical expression is false only when<br />

both operands are false.<br />

118 Chapter 9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!