Bài 5. Toán tử và lệnh gán
Operator | Meaning | Example |
+ | Cộng | x + y+ 2 |
- | Trừ | x - y- 2 |
* | Nhân | x * y |
/ | Chia | x / y |
% | Lấy phần dư của phép chia (mod) | x % y |
// | Lấy phần nguyên của phép chia (div) | x // y |
** | Lỹ thừa | x**y (xy) |
Ví dụ:
x = 19
print('x =',x)
y = 4
print('y =',y)
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x % y =',x%y)
print('x ** y =',x**y)
Output:
x = 19 y = 4 x + y = 23 x - y = 15 x * y = 76 x / y = 4.75 x // y = 4 x % y = 3 x ** y = 130321
Operator | Meaning | Example |
> | Lớn hơn | x > y |
< | Nhỏ hơn | x < y |
== | Bằng | x == y |
!= | Khác | x != y |
>= | Lớn hơn hoặc bằng | x >= y |
<= | Nhỏ hơn hoặc bằng | x <= y |
Ví dụ:
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Output:
x > y is False x < y is True x == y is False x != y is True x >= y is False x <= y is True
Operator | Meaning | Example |
and | Và: True khi cả hai đều True | x and y |
or | Hoặc: True nếu một trong hai là True | x or y |
not | Không: True khi False | not x |
Ví dụ:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
x and y is False x or y is True not x is False
Toán tử bitwise dùng để làm việc với các toán hạng nhị phân.
Ví dụ, với x = 10 (0000 1010) và y = 4 (0000 0100)
Operator | Meaning | Example |
& | Bitwise AND | x & y |
| | Bitwise OR | x | y |
~ | Bitwise NOT | ~x |
^ | Bitwise XOR | x ^ y |
>> | Bitwise dịch phải | x >> 2 (dịch phải 2 bít) |
<< | Bitwise dịch trái (chuyển trái | x << 2 (dịch trái 2 bít) |
x = 10
print('x =',x)
y = 4
print('x',y)
print('x & y =',x&y)
print('x | y =',x|y)
print('~x =',~x)
print('x ^ y =',x^y)
print('x >> 2 =',x>>2)
print('x << 2 =',x<<2)
input()
Output:
x = 10 x 4 x & y = 0 x | y = 14 ~x = -11 x ^ y = 14 x >> 2 = 2 x << 2 = 40
Operator | Example | Equivalent to |
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
//= | x //= 5 | x = x // 5 |
**= | x **= 5 | x = x ** 5 |
&= | x &= 5 | x = x & 5 |
|= | x |= 5 | x = x | 5 |
^= | x ^= 5 | x = x ^ 5 |
>>= | x >>= 5 | x = x >> 5 |
<<= | x <<= 5 | x = x << 5 |
Last modified 2yr ago