F F F F F F F F F

Assume the variables a = 2, b = 4, and c = 6. Circle the T or F for each of the following conditions to indicate whether its value is true or false.

Explain how short-circuit evaluation works with the and and o r operators.

Write an i f statement that displays the message "The number is valid" if the value referenced by speed is within the range 0 through 200.

Write an i f statement that displays the message "The number is not valid" if the value referenced by speed is outside the range 0 through 200.

Boolean Variables

CONCEPT: A Boolean variable can reference one of two values: True or False.

Boolean variables are commonly used as flags, which indicate whether specific conditions exist.

So far in this book we have worked with in t, float, and str (string) variables. In addition to these data types, Python also provides a bool data type. The bool data type allows you to create variables that may reference one of two possible values: True or False. Here are examples of how we assign values to a bool variable:

hungry = True sleepy = False

Boolean variables are most commonly used as flags. A flag is a variable that signals when some condition exists in the program. When the flag variable is set to False, it indicates the condition does not exist. When the flag variable is set to True, it means the condition does exist.

For example, suppose a salesperson has a quota of $50,000. Assuming sales references the amount that the salesperson has sold, the following code determines whether the quota has been met:

sales-quota-met = True else:

sales-quota-met = False

As a result of this code, the sales quoi a — met variable can be used as a flag to indicate whether the sales quota has been met. Later in the program we might test the flag in the following way:

if sales-quota-met:

print 'You have met your sales quota!'

This code displays 'You have met your sales quota! ' if the bool variable sales quota— met is True. Notice that we did not have to use the == operator to explicitly compare the sales— quota— metvariable with the value True. This code is equivalent to the following:

print 'You have met your sales quota!'

Checkpoint

4.20 What values can you assign to a bool variable?

4.21 What is a flag variable?

0 0

Post a comment