python3104chm 4.8.8. Function Annotations
for i in range(5):
i += 1
print(i)
1
2
3
4
5
from enum import Enum
class Color(Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
color = Color(input("Enter your choice of 'red','blue' or 'green':"))
match color:
case Color.RED:
print("I see red!")
case Color.GREEN:
print("Grass is green!")
case Color.RED:
print("I'm feeling the blues:(")
Grass is green!
def fib(n):
a, b = 0, 1
while a < n:
print(a, end='')
a, b = b, a+b
print()
fib(10)
0112358
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
[1]
[2]
[3]
def cheeseshop(kind, *arguments, **keywords):
print("--Do you have any", kind, "?")
print("--I'm sorry,we're all our of", kind)
for arg in arguments:
print(arg)
print("-"*40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "it's very runny,sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Micheal Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
--Do you have any Limburger ?
--I'm sorry,we're all our of Limburger
it's very runny,sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Micheal Palin
client : John Cleese
sketch : Cheese Shop Sketch
# Unpackling Argument Lists
args = [3, 6]
list(range(*args))
[3, 4, 5]
def parrot(voltage, state='a stiff', action='voom'):
print("--This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.", end=" ")
print("E's", state, "!")
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
--This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
# Using lists as queues
from collections import deque
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")
queue.popleft()
queue.popleft()
queue
'Eric'
'John'
deque(['Michael', 'Terry', 'Graham'])
# list comprehensions
[(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
combs = []
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
combs.append((x, y))
combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
# Nested List Comprehensions
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]
[[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
transposed =[]
for i in range(4):
transposed_row =[]
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
list(zip(*matrix)) #see unpacking argument lists for details on the asterisk in this line
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
apple
banana
orange
pear
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
if __name__ == "__mian__":
import sys
fib(int(sys.argv[1]))
#you can modify it using standard list operations
import sys
sys.path
['c:\\Users\\Administrator\\Documents',
'c:\\Python310\\python310.zip',
'c:\\Python310\\DLLs',
'c:\\Python310\\lib',
'c:\\Python310',
'',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python310\\site-packages',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python310\\site-packages\\win32\\lib',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python310\\site-packages\\Pythonwin',
'c:\\Python310\\lib\\site-packages']
sys.ps1
sys.ps2
'C>'
'...: '
import sys
dir(sys)
['__breakpointhook__',
'__displayhook__',
'__doc__',
'__excepthook__',
'__interactivehook__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'__stderr__',
'__stdin__',
'__stdout__',
'__unraisablehook__',
'_base_executable',
'_clear_type_cache',
'_current_exceptions',
'_current_frames',
'_deactivate_opcache',
'_debugmallocstats',
'_enablelegacywindowsfsencoding',
'_framework',
'_getframe',
'_git',
'_home',
'_xoptions',
'addaudithook',
'api_version',
'argv',
'audit',
'base_exec_prefix',
'base_prefix',
'breakpointhook',
'builtin_module_names',
'byteorder',
'call_tracing',
'copyright',
'displayhook',
'dllhandle',
'dont_write_bytecode',
'exc_info',
'excepthook',
'exec_prefix',
'executable',
'exit',
'flags',
'float_info',
'float_repr_style',
'get_asyncgen_hooks',
'get_coroutine_origin_tracking_depth',
'getallocatedblocks',
'getdefaultencoding',
'getfilesystemencodeerrors',
'getfilesystemencoding',
'getprofile',
'getrecursionlimit',
'getrefcount',
'getsizeof',
'getswitchinterval',
'gettrace',
'getwindowsversion',
'hash_info',
'hexversion',
'implementation',
'int_info',
'intern',
'is_finalizing',
'last_traceback',
'last_type',
'last_value',
'maxsize',
'maxunicode',
'meta_path',
'modules',
'orig_argv',
'path',
'path_hooks',
'path_importer_cache',
'platform',
'platlibdir',
'prefix',
'ps1',
'ps2',
'ps3',
'pycache_prefix',
'set_asyncgen_hooks',
'set_coroutine_origin_tracking_depth',
'setprofile',
'setrecursionlimit',
'setswitchinterval',
'settrace',
'stderr',
'stdin',
'stdlib_module_names',
'stdout',
'thread_info',
'unraisablehook',
'version',
'version_info',
'warnoptions',
'winver']
import builtins
dir(builtins)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
'BytesWarning',
'ChildProcessError',
'ConnectionAbortedError',
'ConnectionError',
'ConnectionRefusedError',
'ConnectionResetError',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EncodingWarning',
'EnvironmentError',
'Exception',
'False',
'FileExistsError',
'FileNotFoundError',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'InterruptedError',
'IsADirectoryError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'ModuleNotFoundError',
'NameError',
'None',
'NotADirectoryError',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'PermissionError',
'ProcessLookupError',
'RecursionError',
'ReferenceError',
'ResourceWarning',
'RuntimeError',
'RuntimeWarning',
'StopAsyncIteration',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'TimeoutError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'WindowsError',
'ZeroDivisionError',
'__IPYTHON__',
'__build_class__',
'__debug__',
'__doc__',
'__import__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'abs',
'aiter',
'all',
'anext',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'copyright',
'credits',
'delattr',
'dict',
'dir',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'execfile',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'license',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'runfile',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']
Packages
Package are a way of structuring Python's module namespace by using "dotted module names".
import re
def replace_num(str):
numDict = {'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
print(str.group())
return numDict[str.group()]
my_str = '2018年6月7号'
a = re.sub(r'(\d)', replace_num, my_str)
print(a) #每次匹配一个数字,执行函数,获取替换后的值
2
0
1
8
6
7
二〇一八年六月七号