13 ต.ค. 2023 เวลา 00:05 • การศึกษา

EP 16:: Python Operators

ใน Python, มี operators หลายประเภทที่คุณสามารถใช้งานได้ ดังนี้:
1. **Arithmetic Operators (ตัวดำเนินการทางคณิตศาสตร์)**: ใช้สำหรับการทำงานทางคณิตศาสตร์ เช่น `+`, `-`, `*`, `/`, `%` (modulo), `**` (exponentiation), `//` (floor division)
```python
x = 10
y = 3
print(x + y) # 13
print(x - y) # 7
print(x * y) # 30
print(x / y) # 3.3333333333333335
print(x % y) # 1
print(x ** y) # 1000
print(x // y) # 3
```
2. **Comparison Operators (ตัวดำเนินการเปรียบเทียบ)**: ใช้สำหรับการเปรียบเทียบค่าของตัวแปร เช่น `==`, `!=`, `>`, `<`, `>=`, `<=`
```python
x = 10
y = 3
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
```
3. **Logical Operators (ตัวดำเนินการทางตรรกศาสตร์)**: ใช้สำหรับการทำงานทางตรรกศาสตร์ เช่น `and`, `or`, `not`
```python
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
```
4. **Assignment Operators (ตัวดำเนินการกำหนดค่า)**: เช่น `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `//=`
```python
x = 10
x += 3 # Same as x = x + 3, so x now is 13
x -= 3 # Same as x = x - 3, so x now is 10 again
```
5. **Bitwise Operators (ตัวดำเนินการทางบิต)**: เช่น `&` (and), `|` (or), `^` (xor), `~` (not), `<<` (shift left), `>>` (shift right)
```python
x = 10 # Binary: 1010
y = 4 # Binary: 0100
print(x & y) # Binary AND, result is 0 (0000 in binary)
print(x | y) # Binary OR, result is 14 (1110 in binary)
print(x ^ y) # Binary XOR, result is 14 (1110 in binary)
```
6. **Identity Operators (ตัวดำเนินการตรวจสอบตัวตน)**: เช่น `is`, `is not`
```python
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
# returns True because z is the same object as x
print(z is x)
# returns False because x is not the same object as y, even if they have the same content
print(x is y)
# to demonstrate the difference between "is" and "==": this comparison returns True because x's content is equal to y's content
print(x == y)
```
7. **Membership Operators (ตัวดำเนินการตรวจสอบสมาชิก)**: เช่น `in`, `not in`
```python
x = ["apple", "banana"]
# returns True because a sequence with the value "banana" is in the list
print("banana" in x)
# returns False because a sequence with the value "grape" is not in the list
print("grape" not in x)
```
โฆษณา