Operators in Python

2026-10-28来源 dev.to PythonEnglish

In Python, operators are symbols used to perform operations on variables and values.
1. Arithmetic operators
Used for mathematical calculations.

+ Addition 10 + 5 15 - Subtraction 10 - 5 5 * Multiplication 10 * 5 50 / Division 10 / 5 2.0 // Floor division 10 // 3 3 % Modulus (remainder) 10 % 3 1 ** Power 2 ** 3 8 

2. Comparison operators
Used to compare two values. The result is True or False.

== Equal to 5 == 5 True != Not equal to 5 != 3 True > Greater than 5 > 3 True < Less than 5 < 3 False >= Greater than or equal to 5 >= 5 True <= Less than or equal to 3 <= 5 True 

Important: Python uses == for equality. It does not have JavaScript's strict equality operator ===.

3. Assignment operators
Used to assign or update values.

= x = 10 Assign 10 to x += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 2 x = x * 2 /= x /= 2 x = x / 2 %= x %= 3 x = x % 3 //= x //= 2 x = x // 2 **= x **= 2 x = x ** 2 

4. Logical operators
Used to combine conditions.

and -Both conditions must be true 5 > 2 and 8 > 3 True or -At least one condition must be true 5 < 2 or 8 > 3 True not -Reverses the result not True False 

Example:

age = 25 if age >= 18 and age <= 60: print("Eligible") 

Output:

Eligible 

5. Membership operators
Check whether a value exists inside a sequence, such as a string or list.

in "a" in "apple" True not in "z" not in "apple" True 

Example:

fruits = ["apple", "banana", "orange"] print("apple" in fruits) 

Output:

True 

**

  1. Identity operators** Check whether two variables refer to the same object.
is Same object is not Not the same object 
a = None print(a is None) # True 

Use is None to check whether a variable is None. Do not use is as a replacement for == when comparing ordinary values.

7. Bitwise operators
Bitwise operators in Python work on the binary representation (0s and 1s) of integers.

& AND \| OR ^ XOR ~ NOT << Left shift >> Right shift 

1. Examples of bitwise operators
& — AND
Returns 1 only when both bits are 1.

a = 5 # Binary: 0101 b = 3 # Binary: 0011  print(a & b) 

Output: 1

| — OR
Returns 1 when at least one bit is 1.

print(5 | 3) 

Output: 7
Explanation:

 0101 (5) | 0011 (3) ------ 0111 (7) 

^ — XOR
Returns 1 when the two bits are different.

print(5 ^ 3) 

Output: 6

Explanation:

 0101 (5) ^ 0011 (3) ------ 0110 (6) 

~ — NOT
Reverses the bits. In Python, ~x equals -x - 1.

print(~5) 

Output: -6

<< — Left shift
Shifts bits to the left. For non-negative integers, shifting left by one position multiplies the value by 2.

print(5 << 1) print(5 << 2) 

Output:

10 20 

Explanation:

5 = 0101 5 << 1 = 1010 (10) 5 << 2 = 10100 (20) 

>> — Right shift
Shifts bits to the right. For non-negative integers, shifting right by one position is equivalent to floor-dividing by 2.

print(5 >> 1) print(5 >> 2) 

Output:

2 1 

Explanation:

5 = 0101 5 >> 1 = 0010 (2) 5 >> 2 = 0001 (1) 

原文:https://www.a8q9.cn/en/article/operators-in-python-2a17ec.html

相关文章