至此,Python基础语法体系已经全部结束!简要回顾一下
N越大,比赛结果越科学
假设新的比赛规则(早年女排规则):
整体步骤:打印介绍信息->获取参数->模拟->输出结果
通过四个函数实现这件事
import random
def print_info():
print("欢迎来到体育竞技模拟器")
print("请输入A和B队员的能力(0到1之间的小数)")
def get_inputs():
a = eval(input("请输入A的能力(0-1):"))
b = eval(input("请输入B的能力(0-1):"))
n = eval(input("请输入要模拟的次数:"))
return a,b,n
def simulate_N(a,b,n):
win_a, win_b = (0, 0)
for i in range(n):
score_a ,score_b = simulate_one(a,b)
if score_a > score_b:
win_a+=1
else:
win_b+=1
return win_a,win_b
def simulate_one(a,b):
score_a,score_b = (0,0)
ball_control_list = {"A","B"}
ball_control = ball_control_list.pop() # 假定A或者B先发球
while not game_over(score_a,score_b):
# 根据能力判定谁赢了这一局
# 假定发球和能力十分相关
if ball_control== "A":
if random.random()<a:
score_a+=1
else:
ball_control = "B"
else:
if random.random()<b:
score_b+=1
else:
ball_control = "A"
return score_a,score_b
def game_over(score_a,score_b):
return score_a==15 or score_b==15
def print_summary(wins_a,wins_b):
n = wins_a+wins_b
print("共模拟比赛{}场".format(n))
print("A获胜{}场,胜率为{}".format(wins_a,wins_a/n))
print("B获胜{}场,胜率为{}".format(wins_b,wins_b/n))
print_info()
a,b,n = get_inputs()
win_a,win_b = simulate_N(a,b,n)
print_summary(win_a,win_b)
初步结论:差之毫厘,谬以千里。一点点能力的不同会导致悬殊的差距。
但是如果水平相近,那么才是比分变化微妙的时刻。
计算思维:设计和构造,计算机为代表,汉诺塔递归
计算思维的特征:抽象和自动化
例1:计算1+2+...+100
例2:圆周率的计算
例3:汉诺塔思维
例4:天气预报
例5:量化分析
现在:历史大量数据,进行机器学习,完成预测,自动交易
计算思维基于计算机强大的算力和海量的数据
一些可能的方法:
用户体验是产品到用户的关键环节,也决定了产品能不能服务更多用户。
开发的四个步骤:
PyPI: Python Package Index
由PSF进行维护
在里面可以充分浏览检索第三方库,找到合适的第三方库开发程序
安装Python库一般用三种方法:
!pip3 -h
Usage: pip3 <command> [options] Commands: install Install packages. download Download packages. uninstall Uninstall packages. freeze Output installed packages in requirements format. list List installed packages. show Show information about installed packages. check Verify installed packages have compatible dependencies. config Manage local and global configuration. search Search PyPI for packages. cache Inspect and manage pip's wheel cache. index Inspect information available from package indexes. wheel Build wheels from your requirements. hash Compute hashes of package archives. completion A helper command used for command completion. debug Show information useful for debugging. help Show help for commands. General Options: -h, --help Show help. --debug Let unhandled exceptions propagate outside the main subroutine, instead of logging them to stderr. --isolated Run pip in an isolated mode, ignoring environment variables and user configuration. -v, --verbose Give more output. Option is additive, and can be used up to 3 times. -V, --version Show version and exit. -q, --quiet Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels). --log <path> Path to a verbose appending log. --no-input Disable prompting for input. --proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port. --retries <retries> Maximum number of retries each connection should attempt (default 5 times). --timeout <sec> Set the socket timeout (default 15 seconds). --exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort. --trusted-host <hostname> Mark this host or host:port pair as trusted, even though it does not have valid or any HTTPS. --cert <path> Path to PEM-encoded CA certificate bundle. If provided, overrides the default. See 'SSL Certificate Verification' in pip documentation for more information. --client-cert <path> Path to SSL client certificate, a single file containing the private key and the certificate in PEM format. --cache-dir <dir> Store the cache data in <dir>. --no-cache-dir Disable the cache. --disable-pip-version-check Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index. --no-color Suppress colored output. --no-python-version-warning Silence deprecation warnings for upcoming unsupported Pythons. --use-feature <feature> Enable new functionality, that may be backward incompatible. --use-deprecated <feature> Enable deprecated functionality, that will be removed in the future.
pip3命令简要介绍:
pip3是最主要的方法,需要使用互联网连接
! pip3 search blockchain # 即将被废弃
! pip_search blockchain # 正确用法
ERROR: XMLRPC request failed [code: -32500]
RuntimeError: PyPI's XMLRPC API is currently disabled due to unmanageable load and will be deprecated in the near future. See https://status.python.org/ for more information.
结合特定的Python开发工具进行安装:如Anaconda。
内含800+数据分析的第三方库,并且支持多种开发环境,如Jupyter。
有些第三方库只提供源代码,需要编译后才能安装。
如果系统没有编译环境,那么pip3后无法安装。
所以可以下载别人提供好的可执行文件,这样下载完之后,使用pip3 install即可安装。
os库提供通用的、基本的操作系统交互功能。
使用os.path子库进行路径操作
用于处理文件路径。常见方法如下:
import os.path
os.chdir("/Users/caiguu/PycharmProjects/pythonLearn")
print(os.path.abspath("data.csv"))
print(os.path.normpath(os.path.abspath("data.csv")))
print(os.path.relpath("data.csv"))
print(os.path.relpath("/System/Applications/Messages.app"))
print(os.path.dirname("/System/Applications/Messages.app"))
print(os.path.basename("/System/Applications/Messages.app"))
print(os.path.join("/System","Applications","Messages.app"))
print(os.path.exists("/System/Applications/Messages.app"))
print(os.path.exists("/System/Applications/QQ.app"))
print(os.path.isfile("/System/Applications/Messages.app"))
print(os.path.isdir("/System/Applications/Messages.app")) #很显然macOS中的.app都是目录
print(os.path.isfile('data.csv'))
/Users/caiguu/PycharmProjects/pythonLearn/data.csv /Users/caiguu/PycharmProjects/pythonLearn/data.csv data.csv ../../../../System/Applications/Messages.app /System/Applications Messages.app /System/Applications/Messages.app True False False True True
下面是几个与文件访问时间相关的方法:
import os.path
print(os.path.getatime("data.csv")) #access
print(os.path.getmtime("data.csv")) #modify
print(os.path.getctime("data.csv")) #create
1645429359.6352324 1645354605.9654377 1645354605.9654377
最后一个:
print(os.path.getsize("data.csv"))
232
os.system("/Applications/云天气.app/Contents/MacOS/云天气")
2022-02-22 16:11:16.493 云天气[2563:2007491] *** WARNING: Textured window <AtomNSWindow: 0x7f800af2e0b0> is getting an implicitly transparent titlebar. This will break when linking against newer SDKs. Use NSWindow's -titlebarAppearsTransparent=YES instead. https://mtapi.ruanmei.com/api/calendar/getfestival?appver=1.02&platform=macos&abestmorale=true Error: 404 Not Found at /Applications/云天气.app/Contents/Resources/app.asar/src/utils/fetch.js:1:550 at processTicksAndRejections (internal/process/task_queues.js:86:5)
0
返回了一个0,表示程序正确运行。
同时可以看到,这个程序弹出的警告也可以被输出。
也可以指定一些参数。
掌握了这个os.system,就具备了调用其他程序的能力。
os.chdir("/Users/caiguu/PycharmProjects/pythonLearn")
print(os.getcwd())
print(os.getlogin())
print(os.cpu_count())
print(os.urandom(12))
/Users/caiguu/PycharmProjects/pythonLearn caiguu 10 b'+Y\xca\x9b\x0fT\x0cXV\xb1\xc2b'
可以看出我当前路径,登录名,我的CPU是10核心的。
随机字符串由于有的字符不能被有效打印,所以不能打印的是16进制的形式,能打印的是字符的形式。
一个字符占用一个字节。
import os
libs = {"numpy","matplotlib","pillow","sklearn","requests","jieba"\
,"beautifulsoup4","wheel","sympy","pandas"}
try:
for lib in libs:
os.system("pip3 install "+lib)
print("Finished")
except:
print("Failed!")
Requirement already satisfied: wheel in /opt/homebrew/lib/python3.10/site-packages (0.37.0)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Requirement already satisfied: beautifulsoup4 in /opt/homebrew/lib/python3.10/site-packages (4.10.0) Requirement already satisfied: soupsieve>1.2 in /opt/homebrew/lib/python3.10/site-packages (from beautifulsoup4) (2.3.1)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x1055da5c0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known')': /simple/pandas/
Collecting pandas Downloading pandas-1.4.1-cp310-cp310-macosx_11_0_arm64.whl (10.5 MB) Requirement already satisfied: python-dateutil>=2.8.1 in /opt/homebrew/lib/python3.10/site-packages (from pandas) (2.8.2) Requirement already satisfied: numpy>=1.21.0 in /opt/homebrew/lib/python3.10/site-packages (from pandas) (1.22.2) Collecting pytz>=2020.1 Downloading pytz-2021.3-py2.py3-none-any.whl (503 kB) Requirement already satisfied: six>=1.5 in /opt/homebrew/lib/python3.10/site-packages (from python-dateutil>=2.8.1->pandas) (1.16.0) Installing collected packages: pytz, pandas Successfully installed pandas-1.4.1 pytz-2021.3
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Requirement already satisfied: jieba in /opt/homebrew/lib/python3.10/site-packages (0.42.1)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Requirement already satisfied: requests in /opt/homebrew/lib/python3.10/site-packages (2.27.1) Requirement already satisfied: charset-normalizer~=2.0.0 in /opt/homebrew/lib/python3.10/site-packages (from requests) (2.0.12) Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/homebrew/lib/python3.10/site-packages (from requests) (1.26.8) Requirement already satisfied: certifi>=2017.4.17 in /opt/homebrew/lib/python3.10/site-packages (from requests) (2021.10.8) Requirement already satisfied: idna<4,>=2.5 in /opt/homebrew/lib/python3.10/site-packages (from requests) (3.3)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Requirement already satisfied: matplotlib in /opt/homebrew/lib/python3.10/site-packages (3.5.1) Requirement already satisfied: cycler>=0.10 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (0.11.0) Requirement already satisfied: packaging>=20.0 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (21.3) Requirement already satisfied: numpy>=1.17 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (1.22.2) Requirement already satisfied: pillow>=6.2.0 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (9.0.1) Requirement already satisfied: kiwisolver>=1.0.1 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (1.3.2) Requirement already satisfied: pyparsing>=2.2.1 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (3.0.6) Requirement already satisfied: python-dateutil>=2.7 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (2.8.2) Requirement already satisfied: fonttools>=4.22.0 in /opt/homebrew/lib/python3.10/site-packages (from matplotlib) (4.29.1) Requirement already satisfied: six>=1.5 in /opt/homebrew/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Collecting sympy Downloading sympy-1.9-py3-none-any.whl (6.2 MB) Collecting mpmath>=0.19 Downloading mpmath-1.2.1-py3-none-any.whl (532 kB) Installing collected packages: mpmath, sympy
WARNING: The script isympy is installed in '/opt/homebrew/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Successfully installed mpmath-1.2.1 sympy-1.9 Requirement already satisfied: pillow in /opt/homebrew/lib/python3.10/site-packages (9.0.1)
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Collecting sklearn Using cached sklearn-0.0.tar.gz (1.1 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting scikit-learn Downloading scikit_learn-1.0.2-cp310-cp310-macosx_12_0_arm64.whl (6.9 MB) Requirement already satisfied: scipy>=1.1.0 in /opt/homebrew/lib/python3.10/site-packages (from scikit-learn->sklearn) (1.8.0) Requirement already satisfied: numpy>=1.14.6 in /opt/homebrew/lib/python3.10/site-packages (from scikit-learn->sklearn) (1.22.2) Collecting threadpoolctl>=2.0.0 Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB) Collecting joblib>=0.11 Using cached joblib-1.1.0-py2.py3-none-any.whl (306 kB) Building wheels for collected packages: sklearn Building wheel for sklearn (setup.py): started Building wheel for sklearn (setup.py): finished with status 'done' Created wheel for sklearn: filename=sklearn-0.0-py2.py3-none-any.whl size=1309 sha256=56b44a1a6fff8d864a17fd1ea785329c20765ff7e6e784430acb56237c6f9600 Stored in directory: /Users/caiguu/Library/Caches/pip/wheels/9b/13/01/6f3a7fd641f90e1f6c8c7cded057f3394f451f340371c68f3d Successfully built sklearn Installing collected packages: threadpoolctl, joblib, scikit-learn, sklearn Successfully installed joblib-1.1.0 scikit-learn-1.0.2 sklearn-0.0 threadpoolctl-3.1.0
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
Requirement already satisfied: numpy in /opt/homebrew/lib/python3.10/site-packages (1.22.2) Finished
WARNING: You are using pip version 21.3.1; however, version 22.0.3 is available. You should consider upgrading via the '/opt/homebrew/opt/python@3.10/bin/python3.10 -m pip install --upgrade pip' command.
根据输出,我们看到成功安装了。
其实用pip3 install -r requirements.txt更为常见,直接安装全部依赖。