Python 3.9 新功能

本文章並未列出Python 3.9的所有新增功能,如果要查看所有新增功能,請參考官方文件:What’s New In Python 3.9 — Python 3.12.0 documentation

:one: 新增dict的union operators運算子

:computer: Python 3.8.7

import sys
print(sys.version)
# 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)]

dict1={"a":10, "b":20}
dict2={"b":30, "c":40}
dict3={**dict1, **dict2}
print(dict3)
# {'a': 10, 'b': 30, 'c': 40}

dict3=dict1|dict2
# TypeError: unsupported operand type(s) for |: 'dict' and 'dict'

dict1.update(dict2)
print(dict1)
# {'a': 10, 'b': 30, 'c': 40}

:computer: Python 3.9

import sys
print(sys.version)
# 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]
dict1={"a":10, "b":20}
dict2={"b":30, "c":40}
dict3=dict1|dict2
print(dict3)
# {'a': 10, 'b': 30, 'c': 40}

dict1|=dict2
print(dict1)
# {'a': 10, 'b': 30, 'c': 40}

:two: string新功能:移除前綴詞

:computer: Python 3.9

"Hello World".removeprefix("Hello")
# ' World'

"Hello World Hello".removeprefix("Hello")
# ' World Hello'
# 只會移除前綴詞,後面的 'Hello' 不會受影響

"Hello World Hello".removesuffix("Hello") # 移除後綴詞
# 'Hello World '

:three: 增強型別的範圍

:computer: Python 3.8.7

myvar: int = 10

def myfunction(myparam: int) -> int:
    return 10

:x: TypeError: 'type' object is not subscriptable

mylist: list[int] = [10, 20, 30]
# TypeError: 'type' object is not subscriptable

:computer: Python 3.9

mylist: list[int] = [10, 20, 30]
print(mylist)
# [10, 20, 30]

:four: 數學模組功能增強

  1. math.gcd(*integers):找最大公因數,Python 3.5後新增此功能
  2. math.lcm(*integers):找最小公倍數,Python 3.9後新增此功能

Python 3.5後增加最大公因數功能,但只能找兩個數值之間的最大公因數。Python 3.9前,只能輸入兩個數值;Python3.9後,可以輸入多個數值。

:computer: Python 3.8.7

import math
math.gcd(15, 25)
# 5

:x: TypeError: gcd expected 2 arguments, got 3

math.gcd(15, 25, 35)
# TypeError: gcd expected 2 arguments, got 3

:x:Python 3.9之前沒有math.lcm(尋找最小公倍數)功能

math.lcm(5,15)
# AttributeError: module 'math' has no attribute 'lcm'

Python 3.9開放尋找多於兩個數值的最大公因數

:computer: Python 3.9

import math
math.gcd(5, 15, 30)
# 5

math.gcd(5, 15, 30, 123)
# 1

math.gcd(5,7,0)
# 1

math.gcd(5,0)
# 5

:o: Python 3.9後新增math.lcm尋找最小公倍數功能,而且支援多於2個數值輸入

math.lcm(5,15)
# 15

math.lcm(5,15,23)
# 345

完整數學函數請參考官方文件:math — Mathematical functions — Python 3.12.0 documentation

2個讚