Introduction
Most of the logic lines you write containExpression. A simple example of an expression is2 + 3. An expression can be divided into operators and operands.
OperatorIs to execute a task. operators can be represented by a symbol or keyword, such+. The operator needs data to execute its functions. The data is namedOperands. In the preceding example,2And3Is the operand.
Operator
Here we will briefly introduce operators and their usage:
You can use the following example for interactive verification in the python Interpreter. For example, verify2 + 3In the python interpreter prompt, enter:
>>> 2 + 35>>> 3 * 515>>>
Operators and their usage
Operator |
Name |
Purpose |
Example |
+ |
Add |
Add two operands |
3 + 5Get8.'A' + 'B'Get'AB'. |
- |
Subtraction |
Find the difference between the two numbers. If the first operand is not written, the default value is 0. |
-5.2A negative number,50-24Get26. |
* |
Multiplication |
Returns the product of two numbers or a string that repeats several times. |
2*3Get6.'La '* 3Get'Lala'. |
** |
Power |
Returns the Power Y of X. |
3 ** 4Get81(3*3*3*3) |
/ |
Division |
Divide X by Y. |
4/3Get1.3333333333333333. |
// |
Integer Division |
Returns the largest integer quotient. |
4 // 3Get1. |
% |
Modulo |
Returns the remainder. |
8% 3Get2.-25.5% 2.25Get1.5. |
< |
Left Shift |
This operation moves several bits to the left. (Numbers are expressed in binary in memory) |
2 <2Get8.2In binary format10. The result is obtained after the Left shift is two bits.1000In decimal format8. |
> |
Right Shift |
Move several bit numbers to the right of the operand. |
11> 1Get5,11In binary format1011, Right shift after one digit to get101In decimal format5. |
& |
Bitwise AND |
The bitwise and of the number. |
5 & 3Get1. |
| |
By bit or |
Number by bit or. |
5 | 3Get7. |
^ |
Bitwise OR |
The bitwise XOR of a number. |
5 ^ 3Get6. |
~ |
Flip by bit |
The bitwise flip of X is-(x + 1 ). |
~ 5Get-6. |
< |
Less |
Returns whether X is less than Y. Returns a Boolean value for all comparison operators.TrueOrFalse. Note that boolean values are sensitive. |
5 <3GetFalse,3 <5GetTrue. Comparison operators can be connected at will, as shown in figure3 <5 <7GetTrue. |
> |
Greater |
Returns whether X is greater than Y. |
5> 3GetTrue. If both operators are numbers, the interpreter converts them to the same type before comparison. OtherwiseFalse. |
<= |
Less than or equal |
Returns whether X is less than or equal to y. |
X = 3; y = 6; x <= yReturnTrue. |
> = |
Greater than or equal |
Returns whether X is greater than or equal to y. |
X = 4; y = 3; x> = 3GetTrue. |
= |
Equal |
Compare whether the two operands are equal. |
X = 2; y = 2; X = yGetTrue. X = 'str'; y = 'str'; X = yGetFalse. X = 'str'; y = 'str'; X = yGetTrue. |
! = |
Not equal |
Compare whether two operands are not equal. |
X = 2; y = 3; X! = YGetTrue. |
Not |
Boolean |
If X isTrueReturnsFalseAnd vice versa. |
X = true; not XReturnFalse. |
And |
Boolean and |
Regardless of the Y value, if X isFalseThenX and YReturnFalse. |
X = false; y = true; X and YBecause X isFalseReturnFalse. In this example, Python has the known and left ValueFalseInstead of calculating the entire Boolean expression, this is the short-circuit evaluate method. |
Or |
Boolean OR |
If X isTrueReturnsTrueOtherwise, return the Boolean value of Y. |
X = true; y = false; X or YReturnTrue. Boolean or use short-circuit values. |
Shortcuts to mathematical operations and assignment
It is common to assign values to a variable after calculation. Therefore, there are shortcuts for such expressions:
You can set:
a = 2; a = a * 3
Written:
a = 2; a *= 3
Note:Variable = variable operator expressionChangedVariable operator = expression
Operation Sequence
If you encounter a similar2 + 3*4First, add or multiply? Perform multiplication first, as said in high school mathematics. This means that the multiplication operator has a higher priority than the addition operator.
The following table lists the operator priorities in Python in ascending order. Given an expression, python will first calculate the operators and expressions in this table, and then calculate the operators and expressions on the top.
This table is taken from Python reference manual and contains all operators. We recommend that you use parentheses to mark parts with higher priority, which makes the program readable. For details, see change the computing order.
Operator priority
Operator |
Description |
Lambda |
Lambda expressions |
Or |
Boolean OR |
And |
Boolean and |
Not x |
Boolean |
In, not in |
Member Testing |
Is, is not |
Identity Test |
<, <=,>, >= ,! =, = |
Comparison Operators |
| |
By bit or |
^ |
Bitwise OR |
& |
Bitwise AND |
<,> |
Displacement |
+ ,- |
Addition and subtraction |
*,/, //, % |
Multiplication, division, and remainder |
+ X,-x |
Positive and Negative |
~ X |
Non-bitwise |
** |
Power |
X. Attribute |
Attribute reference |
X [Index] |
Subscript |
X [index1: index2] |
Addressing segment |
F (arguments ...) |
Function call |
(Expressions ,...) |
Show bindings or tuples |
[Expressions,...] |
Display list |
{Key: datum ,...} |
Display dictionary |
Operators that are not yet exposed in the table will be described in subsequent sections.
YesSame priorityThe operator is located in the same row in the preceding table. For example+And-Has the same priority.
Change computing order
Brackets can be used to increase the readability of expressions. For example2 + (3*4)It is better than the knowledge that requires operator priority.2 + 3*4Better understanding. However, avoid using parentheses too much, for example(2 + (3*4 )).
Brackets can also be used to change the operation sequence, for example, in(2 + 3) * 4Brackets enable the expression to perform addition before multiplication.
Combination Law
The operator is calculated from left to right with the same priority, for example2 + 3 + 4Equivalent(2 + 3) + 4. Other operators, such as the value assignment operator, are calculated from the right to the left, for exampleA = B = CEquivalentA = (B = C).
Expression
Example:
#!/usr/bin/python# Filename: expression.pylength = 5breadth = 2area = length * breadthprint('Area is', area)print('Perimeter is', 2 * (length + breadth))
Output:
$ python expression.py Area is 10 Perimeter is 14
Working principle:
The length and width of the rectangle are stored in variables with the same name. We can obtain the two values by calculating the area and perimeter expressions. We set the expressionLength * breadthThe value is stored in the VariableAreaAnd usePrintThe function prints the variable value. In the second case, we usePrintFunction print expression2 * (Length + breadth).
In addition'Area is'And VariablesAreaAdding spaces, Python still prints this output beautifully. Python automatically generates a beautiful output format for us and makes the program readable: we do not need to worry about spaces in the output string. This is another example of how Python simplifies the work of programmers.
Summary
We understand the bricks required for writing any program: operators, operands, and expressions. Next we will learn how to use these three methods in the program.