Games
Problems
Go Pro!

# Treating Equations as Values

Reference > Science > Technology > Beginner Programming Tips

A boolean variable is a variable which can hold one of two values. It can be True, or it can be False. Alternately, you could call the two values Yes andNo.

Using a boolean variable gives us another way toToggle A Value; we could use the following bit of code:

Dim MyToggle As Boolean

'Toggle A Boolean Variable
M
yToggle = Not MyToggle

If the value was True, it becomes "Not True", orFalse. And if it was False, it becomes "Not False", orTrue.

So here's a question for you. Suppose you wanted to set MyToggle to True if X is equal to 7, but set it toFalse if X does not equal seven.

Here's one way to do it:

Dim MyBoolean As Boolean
Dim X As Integer

'Set the boolean value
If X = 7 Then
MyBoolean = True
Else
MyBoolean = False
End If

That'll do the trick, but it's actually not the easiest way to do it. Because every equation can be treated as a Boolean value! You see, X either equals seven, or it doesn't equal seven. If X is not equal to seven, then the equation X = 7 is False.

Right?

So take a look at this:

Dim MyBoolean As Boolean
Dim X As Integer

'Set the boolean value
MyBoolean = (X = 7)

To understand how this works, you should think of the second part of the equation (X = 7) as a question. The computer is asking: Is X equal to seven? And the answer to that question is either Yes(True) or No (False). So the entire line of code is really saying: Set MyBoolean to Yes if X equals seven, and No if X does not equal seven.

In other words, it's doing the same thing as the "If-Then-Else" statement shown above, but it's doing it with just one line of code instead of five!

You can get more complicated with this; take a look at the following code:

Dim MyFirstBoolean As Boolean
Dim MySecondBoolean As Boolean
Dim X As Integer
Dim Y as Integer

'Set the boolean values
MyFirstBoolean = (X = 7) Or (Y = 7)
MySecondBoolean = (X = 7) ANd (Y = 7)

This one sets the boolean value to True if either X equals seven or Y equals seven. The second one will only be True if both X and Y are equal to 7.

## Questions

1.
If Y equals 5, and Z equals 10, what will the value of X be if you run this code: X = (Y + Z = 15)?
2.
X = (Y > Z) Or (Y = 20)?
3.
X = (Y < Z) And (Y = 5)?
4.
X = (Y - Z = 0) And (Z = 10)?
Assign this reference page
Random Number Generators
Counting Truth Values

# Blogs on This Site

Reviews and book lists - books we love!
The site administrator fields questions from visitors.