The Goals of this Module

■ Understand comparison operators

■ Be familiar with the differences between numerical, object, and string comparisons

■ Understand logical operators and how they enable you to combine comparisons

So far, the flow of the programs has followed a relatively straight line. The program took a predetermined action based on the user's choice. However, as programs become more sophisticated, they often branch in two or more directions based on whether a condition is True or False. For example, in a calculator program, your code would need to determine whether the user chose addition, subtraction, multiplication, or division before performing the indicated arithmetic operation. Your code would make that determination by comparing the user's choice with the various alternatives. That comparison would be made using a comparison operator.

Comparisons also are often used for error prevention. For example, in the calculator program, before performing division, the program should compare the divisor to zero, because division by zero is illegal and, if performed, will result in a runtime error. If the divisor is equal to zero, the user should be warned and the division not performed. Otherwise, the division may be performed.

There are comparison operators to test for equality, inequality, whether one value is greater (or less) than another, and other tests. Comparison operators may be used not only to compare numerical values, but also for strings or even objects.

A comparison operator can make only one comparison at a time. Sometimes you need to combine several comparisons. To determine if someone is eligible to vote, you have to compare both their age to the minimum voting age and their country of citizenship to being the United States. In this case, both comparisons must evaluate as True or the person is not allowed to vote. However, in other comparisons, only one of two conditions need be True. For example, you may be permitted to attend a movie free if you are either a child or a senior citizen.

You use logical operators to combine several comparisons. The logical operators include And, when both comparisons must evaluate as True for an action to be taken, and Or, when only one of two comparisons must evaluate as True for an action to be taken. The comparison and logical operators lay the groundwork for the following modules: Module 7 on control structures and Module 8 on loops, which use these operators to determine if a condition, or a combination of conditions, evaluate as True or False.

Was this article helpful?

0 0

Post a comment