Python 3 นั้นมีการอัพเดตเวอร์ชันอย่างต่อเนื่อง จนในปัจจุบันก็มีถึงเวอร์ชัน 3.8 กันแล้ว (ก.พ. 63) แน่นอนว่าทุกการอัพเดตก็ต้องมีการปรับปรุงหรือเพิ่มเครื่องมือที่จะช่วยให้ผู้ใช้อย่างเราๆสะดวกสบายขึ้น
ครั้งนี้เราเลยหยิบยกเทคนิคต่างๆที่มีเพิ่มเติมขึ้นมาใน Python 3 มานำเสนอให้คุณได้รู้กัน
1. ปรับแต่งตัวคั่นตอนใช้ print() หลายค่า
print("I", "love you", sep=" don't ")
Output:
I don't love you
2. กำหนดค่าให้ตัวแปรภายในเงื่อนไข
text = 'กล้วยอบเนยโรยเกลือ' if ((newText := 'กล้วยอบเนยเลยกลัว') != text): print(newText)
Output:
กล้วยอบเนยเลยกลัว
3. กำหนดบาง argument ของฟังก์ชัน ให้เป็นแบบ Positional-only
def memo(d, m, y, / , time, note): print(d , m, y , time, note) memo(26, 'Oct', 1995, time='08:00', note='Good Morning') memo(27, 'Dec', 2000, note='WipWap WipWap', time='23:20') memo(30, y=2077, m='Mar')
Output:
26 Oct 1995 08:00 Good Morning 27 Dec 2000 23:20 WipWap WipWap Traceback (most recent call last): File "main.py", line 6, in memo(30, y=2077, m='Mar') TypeError: memo() got some positional-only arguments passed as keyword arguments: 'm, y'
4. จัดรูปแบบ string โดยใช้ตัวแปร
thing = "Coding" print(f"We love {thing}.")
Output:
We love Coding.
5. ใส่ Underscore แทรกในค่าที่เป็นตัวเลขเพื่อความง่ายในการอ่าน
animal = 8_400_084_000 print('I have', animal, 'Alpaca in my house') print(type(animal))
Output:
I have 8400084000 Alpaca in my house <class 'int'>
6. กำหนดชนิดตัวแปรที่ต้องการ
def saySomthing(name: str): print(name + ' is a "Plash Speed" router') saySomthing('PS') saySomthing(555)
Output:
PS is a "Plash Speed" router Traceback (most recent call last): File "main.py", line 5, in saySomthing(555) File "main.py", line 2, in saySomthing print(name + ' is a "Plash Speed" router') TypeError: unsupported operand type(s) for +: 'int' and 'str'
7. ใช้ enum ใน Python
from enum import Enum class Color(Enum): red = 1 green = 2 blue = 3 yello = 4 a = Color(3) print(a)
Output:
Color.blue