Lesson goal: Compound true/false questions

Previous: True/false with variables | Home | Next: The if-statement

In the two lessons (here and here) you learned how to generate true or false answers based on the comparison between numbers. The questions were simple, always asking a single question. What about more complex (or compound) questions? What do we mean?

When you search for a book at the library, you can do a search by subject, say "programming." This might take the form of a line like "subject=programming." If you wanted to narrow your search to look for books about programming by the author "Wirth" then you might submit a compound question like "subject=programming" and "author=wirth." Notice the use of the word "and." Say you wanted books either on programming or Australia. You might do a search like "subject=programming" or "subject=Australia." Notice the use of the word "or." True/false questions in computer programming can also involve the words "and" and "or," and they'd mean just what you'd think.

And and or are logical operators and sit between two single (simple) questions. Both of these take the answers to the individual questions to the left and right of them and combine their answers into another single true or false answer.

and or
Move the mouse over a dotted box for more information.

Here is some code that will choose a random number from -100 to 100 and put it into variable a. Let's do some tests on variable a using and's and or's.

Now you try. Click the "run" button a few times and see if the computer displays true when the number chosen is between 0 and 50. Then try some of the exercises suggested below.

Type your code here:


See your results here:

The code here will not run. Would you fill in and and or an or between the two "simple questions" a > 10 and a < 50, to see if $a>10$ and $a<50$? Once you figure that out, run the code several times (keep clicking the "run" button). If you did it right, you should see a true displayed if $a$ is between 10 and 50.

If you get that figured out, try these:

  • Test if $|a|>50$ which means "a is greater than 50 or a is less than -50."
  • Test if $a$ is positive and $a^2$ is greater than 100.
  • Test if $a$ is less than 1 or greater than 5. This is $a<1$ or $a>5$.
Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.