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

Division Operators ใน Python: / vs // และ Python 2 vs 3

การหารใน Python มีรายละเอียดสำคัญที่แตกต่างระหว่าง Python 2 และ 3 และมีออเปอเรเตอร์ 2 ตัว:

Python 2: การหารขึ้นกับชนิดข้อมูล

>> 20 / 7      # 2 (int / int = int, floor division)
>>> 20.0 / 7  # 2.857... (float / int = float)

สร้างบั๊กง่าย: 18*9/5 + 32 ให้ 64 (ผิด) แต่ 18.0*9/5 + 32 ให้ 64.4 (ถูก)

Python 2.2+: ใส่ // สำหรับ Floor Division

>> 9 // 2     # 4
>>> -9 // 2  # -5 (ปัดลงไป -inf)
>>> 9.0 // 2 # 4.0

Python 3: / เสมอเป็น True Division

>> 18 * 9 / 5 + 32   # 64.4 (ถูกต้องเสมอ)
>>> 18.0 * 9 / 5 + 32  # 64.4

>>> 9 / 2    # 4.5
>>> -9 / 2   # -4.5
>>> 9 // 2   # 4 (floor division ยังคงมี)
>>> -9 // 2  # -5

สรุปตาราง

OperatorPython 2 (int/int)Python 3
/Floor divisionTrue division (float)
//Floor divisionFloor division

แนวทางปฏิบัติ

  • Python 3: ใช้ / สำหรับหารปกติ, // เมื่อต้องการปัดลง
  • Python 2: ใส่ from __future__ import division เพื่อให้ / ทำงานแบบ Python 3
  • หลีกเลี่ยงการพึ่งพา implicit integer division