Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ออเปอเรเตอร์พื้นฐานใน Python (Basic Operators)

ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับออเปอเรเตอร์พื้นฐานใน Python

1. Arithmetic Operators (ออเปอเรเตอร์คณิตศาสตร์)

ใช้สำหรับการคำนวณทางคณิตศาสตร์

ชื่อคำอธิบายสัญลักษณ์
Additionบวกสองจำนวน+
Subtractionลบจำนวนหนึ่งจากอีกจำนวน-
Multiplicationคูณสองจำนวน*
Divisionหารจำนวนหนึ่งด้วยอีกจำนวน/
Floor Divisionหารแล้วปัดเศษลง (คืนค่าจำนวนเต็ม)//
Modulusหาเศษจากการหาร%

ตัวอย่าง

a = 5
b = 2

print(f'Addition: {a + b}')
print(f'Subtraction: {a - b}')
print(f'Multiplication: {a * b}')
print(f'Division: {a / b}')
print(f'Floor Division: {a // b}')
print(f'Modulus: {a % b}')

ผลลัพธ์

Addition: 7
Subtraction: 3
Multiplication: 10
Division: 2.5
Floor Division: 2
Modulus: 1

2. Relational Operators (ออเปอเรเตอร์เชิงสัมพันธ์)

คืนค่า True หรือ False ใช้เปรียบเทียบค่า

ชื่อสัญลักษณ์คำอธิบาย
Greater than>มากกว่า
Greater than or equal to>=มากกว่าหรือเท่ากับ
Less than<น้อยกว่า
Less than or equal to<=น้อยกว่าหรือเท่ากับ
Equal to==เท่ากับ
Not equal to!=ไม่เท่ากับ

ตัวอย่าง

a = 5
b = 2

print(f'Greater than: {a > b}')
print(f'Greater than or equal to: {a >= b}')
print(f'Less than: {a < b}')
print(f'Less than or equal to: {a <= b}')
print(f'Equal to: {a == b}')
print(f'Not equal to: {a != b}')

ผลลัพธ์

Greater than: True
Greater than or equal to: True
Less than: False
Less than or equal to: False
Equal to: False
Not equal to: True

3. Logical Operators (ออเปอเรเตอร์ตรรกะ)

ชื่อสัญลักษณ์คำอธิบาย
andandTrue ถ้าทั้งสองเป็น True
ororFalse ถ้าทั้งสองเป็น False
notnotกลับค่าจริง/เท็จ

ตัวอย่าง

a = True
b = False

print(f'and: {a and b}')
print(f'or: {a or b}')
print(f'not a: {not a}')
print(f'not b: {not b}')

ผลลัพธ์

and: False
or: True
not a: False
not b: True

4. Bitwise Operators (ออเปอเรเตอร์บิตวายส์)

ทำงานระดับบิต

สัญลักษณ์ชื่อตัวอย่าง (5 & 2)
&Bitwise AND0
|Bitwise OR7
~Bitwise NOT-6 (สำหรับ 5)

ตัวอย่าง

a = 5  # 0101
b = 2  # 0010

print(f'Bitwise and: {a & b}')
print(f'Bitwise or: {a | b}')
print(f'Bitwise not a: {~a}')
print(f'Bitwise not b: {~b}')

ผลลัพธ์

Bitwise and: 0
Bitwise or: 7
Bitwise not a: -6
Bitwise not b: -3

5. Assignment Operators (ออเปอเรเตอร์กำหนดค่า)

สัญลักษณ์คำอธิบาย
=กำหนดค่า
+=บวกและกำหนดค่า
-=ลบและกำหนดค่า
*=คูณและกำหนดค่า
/=หารและกำหนดค่า
//=หารปัดเศษและกำหนดค่า
%=หาเศษและกำหนดค่า

ตัวอย่าง

a = 5
print(f'=: {a}')

a += 1; print(f'+=: {a}')
a -= 1; print(f'-=: {a}')
a *= 2; print(f'*=: {a}')
a /= 2; print(f'/=: {a}')
a //= 2; print(f'//=: {a}')
a %= 10; print(f'%=: {a}')

ผลลัพธ์

=: 5
+=: 6
-=: 5
*=: 10
/=: 5.0
//=: 2.0
%=: 2.0

สรุป

Python มีออเปอเรเตอร์ครบครัน 5 กลุ่ม: Arithmetic, Relational, Logical, Bitwise, Assignment การเข้าใจแต่ละกลุ่มช่วยเขียนโค้ดได้มีประสิทธิภาพมากขึ้น หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น