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

ออปเปอเรเตอร์คณิตศาสตร์ (Arithmetic Operators) ใน Python


สมมติ a = 10 และ b = 20

ลำดับออปเปอเรเตอร์และคำอธิบายตัวอย่าง
1+ (Addition)
บวกค่าทั้งสองข้าง
a + b = 30
2- (Subtraction)
ลบขวาจากซ้าย
a - b = -10
3* (Multiplication)
คูณค่าทั้งสองข้าง
a * b = 200
4/ (Division)
หารซ้ายด้วยขวา
b / a = 2
5% (Modulus)
เศษจากการหาร
b % a = 0
6** (Exponent)
ยกกำลัง
a**b = 10^20
7// (Floor Division)
หารปัดลง (ทิ้งทศนิยม) ถ้ามีค่าลบ จะปัดไปทางลบ
9//2 = 4, -11//3 = -4

ตัวอย่างโค้ด

#!/usr/bin/python
a = 21
b = 10
c = 0

c = a + b;  print "Line 1 - Value of c is", c  # 31
c = a - b;  print "Line 2 - Value of c is", c  # 11
c = a * b;  print "Line 3 - Value of c is", c  # 210
c = a / b;  print "Line 4 - Value of c is", c  # 2
c = a % b;  print "Line 5 - Value of c is", c  # 1
a = 2; b = 3
c = a**b;   print "Line 6 - Value of c is", c  # 8
a = 10; b = 5
c = a//b;   print "Line 7 - Value of c is", c  # 2

เอาต์พุต

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2