Brief Introduction
Most of the statements you write (logical rows) contain an expression . A simple expression example is 2 + 3. An expression can be decomposed into operators and operands.
The function of an operator is to accomplish something that is represented by symbols such as + or other specific keywords. Operators require data for operations, and such data is called operands. In this example, 2 and 3 are operands.
operator
We'll take a quick look at the operators and their usage: tips
You can interactively use an interpreter to compute the expression given in the example. For example, to test expression 2 + 3, use an interactive Python interpreter with a prompt:
>>> 2 + 3
5
>>> 3 * 5
15
>>>
Table 5.1 operators and their usage
operator |
name |
Description |
Example |
+ |
Add |
Add two objects |
3 + 5 gets 8. ' A ' + ' B ' gets ' ab '. |
- |
Reducing |
Get negative numbers or a number minus another number |
-5.2 Gets a negative number. 50-24 get 26. |
* |
By |
Multiply two numbers or return a string that is repeated several times |
2 * 3 get 6. ' La ' * 3 gets ' Lalala '. |
** |
Power |
Returns the Y-power of X |
3 * * 4 gets 81 (ie 3 * 3 * 3 * 3) |
/ |
Except |
x divided by Y |
4/3 gets 1 (the integer division gets the integer result). 4.0/3 or 4/3.0 get 1.3333333333333333 |
// |
Take the Divide |
The integer part of the return quotient |
4//3.0 gets 1.0 |
% |
Take the mold |
Returns the remainder of a division |
8%3 got 2. -25.5%2.25 got 1.5. |
<< |
Move left |
Shifts a number of bits to the left a certain number (each number in memory is represented as a bit or binary number, i.e. 0 and 1) |
2 << 2 get 8. --2 is expressed as 10 by bit |
>> |
Move right |
Move a number of bits to the right by a certain number |
One >> 1 get 5. --11 is expressed as 1011 by bit, 1 bits to the right and 101, or 5 in decimal. |
& |
Bitwise AND |
The bitwise of number and |
5 & 3 Get 1. |
| |
by bit or |
Number of bitwise OR |
5 | 3 Get 7. |
^ |
Per-bitwise XOR OR |
The bitwise XOR of the number or |
5 ^ 3 Get 6 |
~ |
Flip by bit |
The bit flip of X is-(x+1) |
~5 Get-6. |
< |
Less than |
Returns whether x is less than Y. All comparison operators return 1 to represent true, and 0 to represent false. This is equivalent to the special variable true and false respectively. Note that these variable names are capitalized. |
5 < 3 returns 0 (that is, false) and 3 < 5 returns 1 (that is, true). Comparisons can be any connection: 3 < 5 < 7 returns TRUE. |
> |
Greater than |
Returns whether x is greater than Y |
5 > 3 returns TRUE. If two operands are numbers, they are first converted to a common type. Otherwise, it always returns false. |
<= |
Less than or equal to |
Returns whether x is less than or equal to Y |
x = 3; y = 6; X <= y returns True. |
>= |
Greater than or equal to |
Returns whether x is greater than or equal to Y |
x = 4; y = 3; X >= y returns True. |
== |
Equals |
Compare objects for Equality |
x = 2; y = 2; x = = y returns True. x = ' str '; y = ' StR '; x = = y returns false. x = ' str '; y = ' str '; x = = y returns True. |
!= |
Not equal to |
Compare two objects for unequal |
x = 2; y = 3; X!= y returns True. |
Not |
Boolean "Non" |
Returns False if X is true. If x is False, it returns true. |
x = True; Not X returns FALSE. |
and |
Boolean "and" |
If x is False,x and Y returns false, it returns the calculated value of Y. |
x = False; y = True; X and Y, which returns false because X is false. Here, Python does not compute y because it knows that the value of the expression must be false (because X is false). This phenomenon is called short-circuit calculation. |
Or |
Boolean "or" |
If x is true, it returns true, otherwise it returns the calculated value of Y. |
x = True; y = False; X or Y returns true. Short-circuit calculations are also applicable here. |
Operator Precedence
If you have an expression like 2 + 3 * 4, do you add first, or do multiplication first. Our high school math tells us that we should do multiplication first-which means that the multiplication operator has precedence over the addition operator.
The following table gives Python operator precedence, from the lowest priority (loosely bound) to the highest priority (most tightly combined). This means that in an expression, Python first computes the operator in the table that is less than the following, and then calculates the operators listed at the top of the table.
The following table (exactly the same as the one in the Python reference manual) has taken into account the complete need. In fact, I recommend that you use parentheses to group operators and operands so that you can clearly point out the sequence of operations and make the program as readable as possible. For example, 2 + (3 * 4) is clearly clearer than 2 + 3 * 4. At the same time, parentheses should be used correctly and should not be overused (e.g. 2 + (3 + 4)).
Table 5.2 Operator Precedence
operator |
Description |
Lambda |
Lambda expression |
Or |
Boolean "or" |
and |
Boolean "and" |
Not X |
Boolean "Non" |
In,not in |
Member Test |
Is,is not |
Identity test |
<,<=,>,>=,!=,== |
Comparison |
| |
by bit or |
^ |
Per-bitwise XOR OR |
& |
Bitwise AND |
<<,>> |
Shift |
+,- |
Addition and subtraction |
*,/,% |
Multiplication, division and remainder |
+x,-x |
PLUS sign |
~x |
Flip by bit |
** |
Index |
X.attribute |
Attribute reference |
X[index] |
Subscript |
X[index:index] |
Addressing segments |
F (Arguments ...) |
Function call |
(Experession,...) |
Binding or tuple display |
[Expression,...] |
List display |
{Key:datum,...} |
Dictionary display |
' Expression,... ' |
String conversions |
The operators that we have not contacted are described in later chapters.
Operators that are listed on the same row in a table have the same precedence. For example, + and-have the same priority. Order of calculation
By default, the operator precedence table determines which operator is evaluated before the other operators. However, if you want to change the order in which they are calculated, you have to use parentheses. For example, if you want the addition to be counted before the multiplication in an expression, then you have to write something like (2 + 3) * 4. Binding Law
Operators are usually combined left to right, that is, operators with the same precedence are evaluated in Left-to-right order. For example, 2 + 3 + 4 is computed (2 + 3) + 4. Some operators, such as assignment operators, are combined right to left, that is, a = b = c is processed as a = (b = c).
An expression Use an expression
Example 5.1 using an expression
#!/usr/bin/python
# Filename:expression.py
Length = 5
Breadth = 2
Area = length * breadth
print ' area are ', area
print ' Perimeter is ', 2 * (length + breadth)
(source file: code/expression.py) output
$ python expression.py
Area is 10
Perimeter is how it works
The lengths and widths of rectangles are stored in variables named by them. We use expressions to compute the area and edge length of a rectangle. The result of our expression length * breadth is stored in the variable area and then printed with the print statement. In another print statement, we use the value of the expression 2 * (length + breadth) directly.
Also, notice how python prints "nice" output. Although we do not specify spaces between ' area ' and ' area ', Python automatically places a space in it so that we can get a clear and beautiful output, and the program becomes more readable (because we don't need to worry about the space between the outputs). This is an example of how Python makes life easier for programmers.
Summarize
We've learned how to use operators, operands, and expressions-these make the basic components of any program. Next, we'll learn how to use these parts in our programs through statements.