### Working with Operators

Operators are the basis for both control and management of data within applications. You use operators to define how one piece of data is compared to another and to modify the information within a single variable. In fact, operators are essential to performing any sort of math-related task and to assigning data to variables in the first place.

When using an operator, you must supply either a variable or an expression. You already know that a variable is a kind of storage box used to hold data. An *expression *is an equation or formula that provides a description of a math- ematical concept. In most cases, the result of evaluating an expression is a Boolean (true or false) value. The following sections describe operators in detail because you use them everywhere throughout the rest of the book.

##### Understanding Python’s one ternary operator

A ternary operator requires three elements. Python supports just one such operator, and you use it to determine the truth value of an expression. This operator takes the following form:

TrueValue if Expression else FalseValue

When the Expression is true, the operator outputs TrueValue. When the expression is false, it outputs FalseValue. As an example, if you type

“Hello” if True else “Goodbye”

the operator outputs a response of ‘Hello’.

However, if you type

“Hello” if False else “Goodbye”

the operator outputs a response of

‘Goodbye’. This is a handy operator for times

when you need to make a quick decision and don’t want to write a lot of code to do it.

One of the advantages of using Python is that it normally has more than one way to do things. Python has an alternative form of this ternary operator — an even shorter shortcut. It takes the following form:

(FalseValue, TrueValue) [Expression]

As before, when Expression is true, the oper ator outputs TrueValue; otherwise, it outputs FalseValue. Notice that the TrueValue and FalseValue elements are reversed in this case. An example of this version is

(“Hello”, “Goodbye”)[True]

In this case, the output of the operator is ‘Goodbye’ because that’s the value in the TrueValue position. Of the two forms, the first is a little clearer, while the second is shorter.

*Defining* *the* *operators*

An *operator *accepts one or more inputs in the form of variables or expressions, performs a task (such as comparison or addition), and then provides an output consistent with that task. Operators are classified partially by their effect and partially by the number of elements they require. For example, a unary opera- tor works with a single variable or expression; a binary operator requires two.

The elements provided as input to an operator are called *operands. *The oper- and on the left side of the operator is called the left operand, while the oper- and on the right side of the operator is called the right operand. The following list shows the categories of operators that you use within Python:

- Unary
- Arithmetic
- Relational

- Logical
- Bitwise
- Assignment
- Membership
- Identity

Each of these categories performs a specific task. For example, the arithme- tic operators perform math-based tasks, while relational operators perform comparisons. The following sections describe the operators based on the category in which they appear.

Unary

Unary operators require a single variable or expression as input. You often use these operators as part of a decision-making process. For example, you might want to find something that isn’t like something else. Table 6-1 shows the unary operators.

**T****able** **6-1 Python** **Unary** **Operators**

** **

*Operator **Description **Example*

~ Inverts the bits in a number so that all the 0 bits become 1 bits and vice versa.

– Negates the original value so that positive becomes negative and vice versa.

+ Is provided purely for the sake of completeness. This operator returns the same value that you provide as input.

~4 results in a value of –5

–(–4) results in 4 and –4

results in –4

+4 results in a value of 4

*Arithmetic*

Computers are known for their capability to perform complex math. However, the complex tasks that computers perform are often based on much simpler math tasks, such as addition. Python provides access to libraries that help you perform complex math tasks, but you can always create your own librar- ies of math functions using the simple operators found in Table 6-2.

###### Table 6-2 Python Arithmetic Operators

** **

*Operator **Description **Example*

+ Adds two values together 5 + 2 = 7

– Subtracts the right operand from the left operand 5 – 2 = 3

* Multiplies the right operand by the left operand 5 * 2 = 10

/ Divides the left operand by the right operand 5 / 2 = 2.5

% Divides the left operand by the right operand and returns the remainder

** Calculates the exponential value of the right operand by the left operand

// Performs integer division, in which the left operand is divided by the right operand and only the whole number is returned (also called floor division)

5 % 2 = 1

5 ** 2 = 25

5 // 2 = 2

*Relational*

The relational operators compare one value to another and tell you when the relationship you’ve provided is true. For example, 1 is less than 2, but 1 is never greater than 2. The truth value of relations is often used to make deci- sions in your applications to ensure that the condition for performing a spe- cific task is met. Table 6-3 describes the relational operators.

###### Table 6-3 Python Relational Operators

** **

*Operator **Description **Example*

== Determines whether two values are equal. Notice that the relational operator uses two equals signs. A mistake many developers make is using just one equals sign, which results in one value being assigned to another.

!= Determines whether two values are not equal. Some older versions of Python allowed you to use the <> oper ator in place of the != operator. Using the <> operator results in an error in current versions of Python.

> Verifies that the left operand value is greater than the right operand value.

1 == 2 is False

1 != 2 is True

1 > 2 is False

*Operator **Description **Example*

< Verifies that the left operand value is less than the right operand value.

>= Verifies that the left operand value is greater than or equal to the right operand value.

<= Verifies that the left operand value is less than or equal to the right operand value.

1 < 2 is True

1 >= 2 is False

1 <= 2 is True

*Logical*

The logical operators combine the true or false value of variables or expres- sions so that you can determine their resultant truth value. You use the logi- cal operators to create Boolean expressions that help determine whether to perform tasks. Table 6-4 describes the logical operators.

###### Table 6-4 Python Logical Operators

** **

*Operator **Description **Example*

and Determines whether both operands are true.

or Determines when one of two operands is true.

not Negates the truth value of a single operand. A true value becomes false and a false value becomes true.

True and True is True True and False is False False and True is False

False and False is False True or True is True

True or False is True False or True is True

False or False is False not True is False

not False is True

*Bitwise*

The bitwise operators interact with the individual bits in a number. For exam- ple, the number 6 is actually 0b0110 in binary.

If your binary is a little rusty, you can use the handy Binary to Decimal to Hexadecimal Converter at http://www.mathsisfun.com/binary-

decimal-hexadecimal-converter.html. You need to enable JavaScript to make the site work.

A bitwise operator would interact with each bit within the number in a spe- cific way. When working with a logical bitwise operator, a value of 0 counts as false and a value of 1 counts as true. Table 6-5 describes the bitwise operators.

###### Table 6-5 Python Bitwise Operators

** **

*Operator **Description **Example*

& (And) Determines whether both individual bits

within two operators are true and sets the resulting bit to true when they are.

| (Or) Determines whether either of the indi vidual bits within two operators is true and sets the resulting bit to true when one of them is.

0b1100 & 0b0110

= 0b0100

0b1100 | 0b0110 =

0b1110

^ (Exclusive or)

~ (One’s complement)

<< (Left shift)

>> (Right shift)

Determines whether just one of the indi vidual bits within two operators is true and sets the resulting bit to true when one is. When both bits are true or both bits are false, the result is false.

Calculates the one’s complement value of a number.

Shifts the bits in the left operand left by the value of the right operand. All new bits are set to 0 and all bits that flow off the end are lost.

Shifts the bits in the left operand right by the value of the right operand. All new bits are set to 0 and all bits that flow off the end are lost.

0b1100 ^ 0b0110 =

0b1010

~0b1100 =

–0b1101

~0b0110 =

–0b0111 0b00110011 << 2 =

0b11001100

0b00110011 >> 2 =

0b00001100

*Assignment*

The assignment operators place data within a variable. The simple assign- ment operator appears in previous chapters of the book, but Python offers a number of other interesting assignment operators that you can use. These other assignment operators can perform mathematical tasks during the assignment process, which makes it possible to combine assignment with a math operation. Table 6-6 describes the assignment operators. For this par- ticular table, the initial value of MyVar in the Example column is 5.

###### Table 6-6 Python Assignment Operators

** **

*Operator **Description **Example*

= Assigns the value found in the right oper and to the left operand.

+= Adds the value found in the right operand to the value found in the left operand and places the result in the left operand.

-= Subtracts the value found in the right operand from the value found in the left operand and places the result in the left operand.

*= Multiplies the value found in the right oper and by the value found in the left operand and places the result in the left operand.

/= Divides the value found in the left operand by the value found in the right operand and places the result in the left operand.

%= Divides the value found in the left operand by the value found in the right operand and places the remainder in the left operand.

**= Determines the exponential value found in the left operand when raised to the power of the value found in the right operand and places the result in the left operand.

//= Divides the value found in the left operand by the value found in the right operand and places the integer (whole number) result in the left operand.

MyVar = 2 results in MyVar containing 2

MyVar += 2 results in MyVar contain ing 7

MyVar = 2 results in MyVar contain ing 3

MyVar *= 2 results in MyVar contain ing 10

MyVar /= 2 results in MyVar contain ing 2.5

MyVar %= 2 results in MyVar contain ing 1

MyVar **= 2 results in MyVar contain ing 25

MyVar //= 2 results in MyVar contain ing 2

Membership

The membership operators detect the appearance of a value within a list or sequence and then output the truth value of that appearance. Think of the membership operators as you would a search routine for a database. You enter a value that you think should appear in the database, and the search routine finds it for you or reports that the value doesn’t exist in the database. Table 6-7 describes the membership operators.

###### Table 6-7 Python Membership Operators

** **

*Operator **Description **Example*

In Determines whether the value in the left operand appears in the sequence found in the right operand.

not in Determines whether the value in

the left operand is missing from the sequence found in the right operand.

“Hello” in “Hello Goodbye” is True

“Hello” not in “Hello Goodbye” is False

*Identity*

The identity operators determine whether a value or expression is of a cer- tain class or type. You use identity operators to ensure that you’re actually working with the sort of information that you think you are. Using the identity operators can help you avoid errors in your application or determine the sort of processing a value requires. Table 6-8 describes the identity operators.

###### Table 6-8 Python Identity Operators

** **

*Operator **Description **Example*

Is Evaluates to true when the type of the value or expression in the right operand points to the same type in the left operand.

is not Evaluates to true when the type of the value or expression in the right operand points to a differ ent type than the value or expression in the left operand.

type(2) is int is True