##What Python Beginners Should Know
1. Preface
Welcome to the "Python Advanced" column! Every student who comes here should have roughly learned a lot of basic knowledge of Python and is in the process of growing up. During this period, I must have encountered a lot of confusion and felt confused about the future direction of study. I fully understand the situation you are facing. I have been exposed to the programming language python since 2007, and have been using python exclusively for all development work since 2009, until today. Looking back on my learning process, I have encountered countless difficulties, and I have also been confused and confused. This column was created to help Python beginners who were as confused as me back then get out of trouble and grow quickly. I hope my experience can really help you.
However, the learning roadmap of many novices is like this: after learning the basic syntax, without understanding the http protocol and Ajax asynchronous requests, they excitedly study crawlers; or, after learning the basic syntax, I went to do visual recognition, and I couldn't even understand the data structure of OpenCV; even after learning the basic grammar, I directly studied the neural network, and the result was that I had to repeat the process from getting started to giving up.
My advice to beginners is not to rush for success, not to aim too high, take one step at a time, work steadily, and success will come naturally. Not rushing for success can avoid detours. Not only will it not slow down your growth, it will actually save you time. Don't aim too high. Achieve one goal and then set the next goal. Through continuous success and progress, you can build self-confidence and stimulate a stronger interest in learning.
Now is better than never, Although never is often better than *right* now.
Cpython
CPython is a Python reference implementation and can be regarded as a standardized version of all other Python derivative distributions. CPython is written in C by a number of key people at the top decision-making level of the Python language. CPython is the most conservative when it comes to optimization. Of course, this is not a shortcoming, but a design orientation. Python maintainers hope to make CPython the most widely compatible and standardized implementation of Python. CPython is best suited for users who require high compatibility and consistency with the Python standard. In addition, CPython is also suitable for professionals who want to use Python in the most basic way and are willing to give up some convenience in order to do so.
Anaconda Python
Anaconda originated from Anaconda Company (formerly known as Continuum Analytics) and is designed to serve Python developers who need support from commercial vendors and have enterprise support services. Key use cases for Anaconda Python include mathematics, statistics, engineering, data analysis, machine learning, and other related applications. Anaconda bundles various commonly used libraries in Python's commercial and scientific usage scenarios - including SciPy, NumPy, Numba, etc., and provides more library access capabilities through a customized package management system.
ActivePython
Similar to Anaconda, ActivePython is also created and maintained by a for-profit company - ActiveState Corporation. The company also sells multiple language runtimes as well as the multilingual Komodo IDE. ActivePython is mainly aimed at enterprise users and data scientists - those who want to use the Python language but do not want to waste a lot of energy on the assembly and management of Python. ActivePython uses the regular pip package manager in Python, but also provides hundreds of common libraries in the form of certified compressed packages, plus some other public libraries with third-party dependencies such as the Intel Math Core Library.
PyPy
PyPy is an alternative to the CPython interpreter that utilizes just-in-time (JIT) compilation to speed up the execution of Python programs. Depending on the actual tasks performed, the performance improvements can be significant. Complaints about Python, especially CPython, mainly revolve around its speed. By default, Python runs far slower than C—the gap can even be hundreds of times faster. PyPy JIT compiles Python code into machine language, resulting in an average running speed of 7.7 times that of CPython. In some specific tasks, its speed-up effect can reach 50 times.
Jython
JVM (Java Virtual Machine) can be used as a runtime option for multiple languages except Java. The long list includes Groovy, Scala, Clojure, Kotlin, Python, and yes, of course, Jython. The biggest drawback of Jython is that it only supports the 2.x version of Python. Support for Python 3.x versions is currently under development, but it will still take quite some time. At the moment, no relevant version has been released.
IronPython
Similar to Jython’s positioning of Python implementation solutions on the JVM, IronPython belongs to a set of .Net runtimes - or CLR ( Common Language Runtime) - Python implementation. IronPython leverages the CLR's DLR (Dynamic Language Runtime) to allow Python programs to run with a level of dynamics equivalent to CPython. Similar to Jython, IronPython currently only supports Python 2.x versions. However, the IronPython 3.x implementation is already under intensive development.
When downloading from the Python official website, please be careful to select the correct version. If it is used for learning, there is no problem in downloading the latest version. If it is used for production, you should consider whether the third-party modules you need for development support the latest version of Python. Don't forget to check the bottom two checkboxes when installing, otherwise it will cause some trouble in subsequent module installation. It is recommended to use the default installation method.
To learn a programming language, you must first find a suitable integrated development tool. It seems that It's a natural thought. why not? The IDE can automatically complete the task, run it with one click, and debug with breakpoints. Using IDE to develop projects is like driving a car with a luxurious interior. Just enjoy the fun of driving. Who cares about how the engine works under the hood? My young colleagues are also fans of IDEs. They initially used pycharm, and later the popular vscode.
However, I always believe that programming is like driving, and programmers are drivers, and they are professional drivers, not white-collar workers and gold-collar workers who regard driving as a commuting skill. Since you are a professional driver, you cannot be satisfied with wearing a bow tie and white gloves to drive a car with luxurious interiors and high-end configurations. Instead, you must have the ability to open the engine hood for repairs and maintenance.
Based on this point of view, I do not recommend that beginners use integrated development tools from the beginning - at least, do not use IDEs in the first week. For an interpreted scripting language like python, a handy editor is enough. On the Linux platform, vim or emacs are both good enough (if you are familiar with both or one of them, please accept my respect); on the Windows platform, I recommend using notepad. The benefits for python beginners to use an editor instead of an IDE are:
解释型语言的优势,就是可以写一句执行一句,想到哪儿写到哪儿,不必像编译型语言那样得把程序全部写完,编译成功后才能运行。我特别喜欢使用python的IDLE,甚至拿它当计算器用。很多时候,我用IDLE验证代码的写法是否正确,查看模块是否安装成功以及版本号。IDLE支持tab键自动补齐,我经常用这个功能查看某个对象的方法和属性。
>>> import numpy as np>>> np.__version__'1.17.0'>>> np.hypot(3,4)5.0>>> def factorial(n): # 计算n的阶乘 if n == 0: # 递归出口 return 1 return n*factorial(n-1) # 向递归出口方向靠近的自身调用>>> factorial(5)120>>> _*2-100140
小技巧
- tab键自动补齐
- 光标移动到执行过的语句上敲击回车,可以重复这个命令
- 下划线(_)可以获取最后一次执行结果
实际上,IDLE就是一个IDE,你可以用它来创建或打开.py脚本文件,可以编辑、运行和调试。
Linux 平台上,一个 python 源码文件应该以下部分组成。Windows 平台上,可以省略第一项。
解释器声明
编码格式声明
模块注释或文档字符串
模块导入
常量和全局变量声明
顶级定义(函数或类定义)
执行代码
附上一个 demo,仅供参考。更详细的编码规范,请参考拙作《我的 Python 编码规范》。
#!/usr/bin/env python# -*- coding: utf-8 -*-"""通常这里是关于本文档的说明(docstring),须以半角的句号、 问号或惊叹号结尾! 本行之前应当空一行,继续完成关于本文档的说明 如果文档说明可以在一行内结束,结尾的三个双引号不需要换行;否则,就要像下面这样 """import os, timeimport datetimeimport mathimport numpy as npimport xlrd, xlwt, xlutilsimport youth_mongodbimport youth_curl BASE_PATH = r"d:\YouthGit"LOG_FILE = u"运行日志.txt"class GameRoom(object): """对局室""" def __init__(self, name, limit=100, **kwds): """构造函数! name 对局室名字 limit 人数上限 kwds 参数字典 """ passdef craete_and_start(): """创建并启动对局室""" passif __name__ == '__main__': # 开启游戏服务 start()
如果你使用的集成开发工具,那么代码的运行和调试,就完全依赖于工具了。如果你使用编辑器开写代码,那就需要手工运行和调试代码。运行代码分成两步:
第1步,打开一个命令行窗口,路径切换到脚本所在的文件夹。我习惯在脚本所在窗口的空白位置(确保没有选中任何对象),按下shift键点击鼠标右键,在弹出的菜单中选择打开Powershell窗口。如下图所示。
第2步,输入python+空格+脚本文件名,回车即可运行。输入脚本文件名时,按tab可以自动补齐。脚本的运行信息、错误信息、运行结果等,都可以显示在这个窗口中。这是最原始的信息。你在其他开发工具中看到信息,都是对这些信息的再加工。
当然,很多编辑器也支持自定义运行命令,可以实现一键运行python脚本。以Notdpan++为例,点击“运行”->“运行”菜单,在弹出的窗口中输入:
cmd /k cd /d “$(CURRENT_DIRECTORY)” & python “$(FULL_CURRENT_PATH)” & echo. & pause & exitCopy after login
因为转义缘故,复制该命令的话,请检查$符号前面是否有\符号,如有,请删除。接下来,点击“保存”按钮,在弹出的窗口中输入新增命令的名称,比如PyRun,定义快捷键,最后点击“确定”按钮。
完成以上设置后,就可以在Notepad++中使用菜单命令或者快捷键运行Python代码了。
手工调试代码的手段不多,除了 print 信息,几乎只有把调试信息写成调试文件了。听起来,好像问题很严重,其实只是理念和取向不同而已。反过来想,手段单一,不恰好意味着简单、简明吗?十几年来,我一直使用 print 调试,坚信没有比它更好的了。
在python语言的发展过程中,安装和管理第三方模块的方法也历经变化。现在,我们终于等来了pip这个近乎完美的工具。pip除了安装(install)和删除(uninstall)这两大功能,还可以指定模块的安装版本(无需预先删除当前已安装版本),可以显示所有已安装的模块,还可以通过 upgrade 自主升级。
很多同学在使用pip时会遇到各种各样稀奇古怪的问题,我在这里解释一下:
同时安装了py2/py3,将会存在多个版本的pip.exe,你如果直接运行:
pip install <模块名>Copy after login
则有可能因为pip.exe版本不对而出错。正确的做法是指定python版本,-m是python解释器的参数,意思是把pip模块做为脚本运行,完整命令如下:
py -3 -m pip install <模块名>Copy after login
如果你使用的是Anaconda Python,或者你是通过IDE来安装模块,则需要检查它们的配置和设置,情况各有不同,没有统一的解决方案。
如果你的计算机只安装了py2 或者 py3,那么上面两种安装方法应该都没有问题。如果你的电脑找不到pip.exe文件,则可以使用这个命令生成:
python -m ensurepipCopy after login
下面,就以同时安装了py2/py3的计算机为例(如果只安装了py2或py3,需要将下面演示中的py -3替换成python),演示pip模块的用法。不管任何情况,我都建议使用-m参数调用pip模块,而不是直接使用 pip.exe 安装模块。
# 虽然可以这样使用pip安装模块(以numpy为例)PS D:\XufiveGit\wxgl> pip install numpy# 但我建议这样使用pipPS D:\XufiveGit\wxgl> py -3 -m pip install numpy# 删除模块PS D:\XufiveGit\wxgl> py -3 -m pip uninstall numpy# 安装模块,指定版本PS D:\XufiveGit\wxgl> py -3 -m pip install numpy=1.15.0# 自主升级PS D:\XufiveGit\wxgl> py -3 -m pip install --upgrade pip# 显示已安装的模块PS D:\XufiveGit\wxgl> py -3 -m pip list Package Version ----------------- ----------- -pencv-python 4.1.1 argh 0.26.2 attrs 19.1.0 Automat 0.7.0 basemap 1.2.0 beautifulsoup4 4.6.3 bleach 3.1.0 cefpython3 66.0... ...
pip也用来安装本地whl文件:
PS D:\PyPackage\py3> py -3 -m pip install .\basemap-1.2.0-cp37-cp37m-win_amd64.whl
感谢大家的阅读,希望大家收益多多。
推荐教程:《python教程》
The above is the detailed content of What Python beginners should know. For more information, please follow other related articles on the PHP Chinese website!