Python Basics Day 3 Operators Encyclopedia

Article Directory

what is an operator

give a chestnut

5 - 3

5 and 3 are operands, -which are operators

arithmetic operator

type

Addition: +
Subtraction: -
Multiplication: *
Division: /
Modulo (remainder): %
Power operation: **
Divisibility: //

example

Take a = 10, b = 20 as an example below
insert image description here

Notice

Operation order:

Python follows the priority of operations in mathematics. The operations in parentheses are performed first, followed by power operations, followed by multiplication, division, and modulo operations, and finally addition and subtraction operations. If multiple operators are mixed together, parentheses can be used to clarify the order of operations.

Integer division and floating point division

In Python, the division operator /returns a floating-point result even if both the dividend and the divisor are integers. If you need to divide evenly, you can use the double slash operator //.

modulo operation

The modulo operator %is used to obtain the remainder when dividing two numbers. Note that the result of the modulo operation has the same sign as the dividend.

For example, 5% of 2 is 1, and -5% of 2 is -1.

exponentiation

The power operator **is used to calculate the power of an exponent of a number.

For example, the result of 2 ** 3 is 8 (that is, 2 to the power of 3).

string concatenation

The addition operator +is used to concatenate strings. When one of the operands is a string, they are concatenated.
For example, "Hello, " + '666' results in "Hello, 666"

Pay attention to operations between integers and floating point numbers

In Python, when integers and floating-point numbers are operated on, the result will be automatically converted to floating-point numbers

For example, the result of 3 + 2.5 is 5.5.

Watch out for overflow issues

When performing numerical operations, you need to pay attention to whether the result will cause data overflow. When using large integers or large floating-point numbers for operations, you need to pay special attention to whether the result exceeds the range of the data type.

assignment operator

type

Simple assignment: =
addition assignment: +=
subtraction assignment: -=
multiplication assignment: *=
division assignment: /=
modulo assignment: %=
exponentiation assignment: **=integer division
assignment: //=

example

insert image description here

Precautions

Assignment order

The assignment operator = assigns the value on the right to the variable on the left. Take care to ensure that the right side of the assignment operator is the value to be assigned to the variable on the left.

multiple assignment

Python supports multiple assignments, that is, assigning different values ​​​​to multiple variables at the same time in one statement .

For example, a, b, c = 10, 20, 30
In this way, variable a can be assigned a value of 10, variable b can be assigned a value of 20, and variable c can be assigned a value of 30.

Incremental assignment operator

Incremental assignment operators (such as +=, -=, *=, etc.) combine arithmetic and assignment operators. They simplify code and perform operations alongside assignments.

For example, a += 5 is equivalent to a = a + 5.

assignment operator chaining

Python allows chained assignments using consecutive assignment operators.

For example, a = b = c = 1 assigns 1 to variables a, b, and c in succession.

Pay attention to the assignment of mutable objects

When you assign a mutable object (such as a list or dictionary) to another variable, you are actually assigning a reference to the object to the variable . This means that modifications made to one variable will affect the other variable . Be aware of the side effects of such references.

Note the assignment of immutable objects

When you assign an immutable object (such as a number, string, or tuple) to another variable, you actually create a new object and assign it to the variable. Changes made to one variable do not affect the other variable .

Precedence of assignment operators

Assignment operators have lower precedence , so when using assignment operators in compound expressions, you need to pay attention to the order of operations and the result.

Replenish
  • a += 5 is equivalent to a = a + 5, but the former directly modifies a, which is faster and the address remains unchanged. The latter is modified first before assignment, and the address may change
    insert image description here
  • In assignment operator chaining, variables share references to the same object. This means that modifications made to one of the variables will affect the other variables. Therefore, care must be taken when using these assignment methods to handle the case of mutable objects to avoid unexpected results.
  • Modifications to mutable objects such as lists show significant differences when multiple assignments and assignment operator chaining are used
# 多重赋值
a = b = [1, 2, 3]
a.append(4)
print(b)  # 输出: [1, 2, 3, 4]

# 赋值运算符链式操作
c = d = [1, 2, 3]
c = c + [4]
print(d)  # 输出: [1, 2, 3]

comparison operator

type

Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=

example

insert image description here

Notice

The results returned by comparison operators are boolean (true or false).
Precision issues when comparing floating point numbers

Due to the precision of floating-point numbers, it is best to use relative error or tolerance error for comparison.

When comparing characters, the ASCII values ​​of the characters are compared.
Strings cannot be compared directly using comparison operators

String-related methods (such as strcmp or related library functions) need to be used to compare strings.

Comparison operators in Python have the property of chained comparisons

Chained comparisons are compared one by one according to the relationship between operands . (C language does not support chained comparison)

For example: the expression 0 <= 1 < 1 == 1 evaluates to False.

First, we compare 0 <= 1, this comparison is correct, because 0 is less than or equal to 1, so the result is True.
We then proceed to compare 1 < 1, which is false because 1 is not less than 1, so the result is False.
Finally, we compare 1 == 1, this comparison is correct, because 1 is equal to 1, so the result is True.

Following the precedence and associativity of comparison operators in Python, the < operator is executed first, followed by the <= and == operators. Thus, the expressions are equivalent to (0 <= 1) and (1 < 1) and (1 == 1).

Since 1 < 1 evaluates to False, the entire expression evaluates to False.

Logical Operators

type

with :and
or :or
not :not

example

Suppose a = 10, b = 20
insert image description here

Notice

Unlimited type

The operands of logical operators in Python can be of any type, not just boolean.

use short-circuit evaluation

Both the logical AND operator and the logical OR operator use a strategy of short-circuit evaluation, where the second condition is evaluated and evaluated only when necessary. (equivalent to &&, || in c language)

attention to priority

Python's logical operators have precedence, and parentheses can be used to clearly specify the order of operations and avoid ambiguity.

bitwise operator

type

Bitwise AND (&): Performs a bitwise AND operation on each corresponding bit of the two operands.
Bitwise OR (|): Performs a bitwise OR operation on each corresponding bit of the two operands.
Bitwise XOR (^): Performs a bitwise XOR operation on each corresponding bit of the two operands.
Bitwise inverse (~): Inverts every bit of the operand, including the sign bit.
Left Shift (<<): Shifts the bits of the operand to the left by the specified number of bits.
Right Shift (>>): Shifts the bits of the operand to the right by the specified number of bits.

example

insert image description here

Notice

Bitwise operators can only be used on operands of integer types (including integer and Boolean types).

If applied to operands of other types, Python will automatically convert them to integers for operation.

Bitwise operators manipulate the binary representation of operands bit by bit.

Therefore, before using bitwise operators, you need to make sure you understand the binary representation of the operands.

For signed integers, Python uses two's complement notation.

This means that for negative numbers, the highest bit is the sign bit (1 for negative numbers) and the remaining bits represent the numeric part.

Bit extension (zero padding) or truncation is performed automatically depending on the number of bits of the operand.

For example, when two operands have different lengths, Python will complement the shorter operand to the same number of bits before performing bit operations.

It is possible to encounter overflow, where the result exceeds what can be represented by the operands.

When using bitwise operators, you should pay attention to the value range of the operands to avoid overflow problems.

member operator

type

Judging whether it is a member: in
Judging whether it is not a member: not in

example

insert image description here

Notice

Membership operators are used to check whether a value exists in a sequence (such as string, list, tuple, etc.).
Membership operators work differently for different types of sequences:
  • String: Membership operator checks if a substring exists in a large string .
  • Lists and Tuples: Membership operators check whether an element exists in a list or tuple .
  • For dictionary-type data structures, membership operators can only be used to check the existence of keys , not the existence of values .

identity operator

type

Judging whether two objects are equal: is
Judging whether two objects are not equal: is not

example

insert image description here

Notice

The identity operator is used to compare whether the identities (memory addresses) of two objects are the same.

==Whether the comparison objects are equal according to the value and type of the data
isaccording to the address of the two

Note the applicability of the identity operator

It is usually used to compare the identity of mutable objects (such as lists, dictionaries) or custom objects.

Generally not used for immutable objects

For immutable objects (like numbers, strings, tuples), their identity cannot be changed, so identity operators don't make much sense for them.

Guess you like

Origin blog.csdn.net/m0_74921567/article/details/132447532