Cause Python beginners!

Foreword

 

Python advanced in the process, I believe that many students should be learning in general a lot of the basics of Python, that is trying to grow. In the meantime, we encountered a lot of confusion, confused about the future direction of learning. I fully understand the situation you are facing. I came into contact with it since 2007 Python programming language to address all development work from 2009 single-use Python, until today. Review their own learning process, have encountered numerous difficulties, had also been confused, puzzled over. This article and subsequent article (https://blog.csdn.net/xufive/category_9506563.html) precisely in order to help as confused as I was out of the woods Python beginners, grow rapidly. I hope my experience can really help you.

Clear learning objectives, not anxious, not ambitious

 

The moment is a noisy, impetuous era. We always attracted large numbers living in hot, little time and opportunity to depth reading and thinking. I have always believed that learning is the need to slowly sink in the heart study, the long-term; at the same time, learning should not be given too utilitarian. A Python programmer's growth roadmap should be like this: basic grammar -> Language Sense Training -> topic Exercise -> points the direction to continue learning -> Intermediate Programmer -> expand the depth and breadth -> advanced programmers.

However, many novice learning road map is like this: After learning basic grammar, do not know HTML and Ajax asynchronous protocol request, excitedly studied reptiles go; or, completion of basic grammar, to engage in visual recognition, even the data structure of OpenCV can not read; even, finished grammar school on the basis of direct study of the neural network, the result is a repeat again from entry to give up.

My advice to beginners is not anxious, not ambitious, step by step, slowly and surely, the power of nature into. Not anxious to avoid detours, not only will not slow down your pace of growth it, it would save you time. Not ambitious to reach a goal, and then develop the next target, the continuous success and progress, build self-confidence, stimulate greater interest in learning.

 

Before you start learning Python, you need to do some preparation

 

Now is better than never,Although never is often better than right now.

This is the Zen of Python in the sentence translated mean, maybe do not do better, but it might as well do without thinking on the hands. Indeed, before you start learning Python, you need to understand some of the background, to make some choices, and be prepared to work on your computer.

Python's various releases

Python is the only son of turtle t, but he has a lot of cousins, more famous there are quite a few. If you're not sure which is more friendly to you, I suggest you choose Python-- lineal and even if you need to deal with the future of his other cousins, that is Shumenshulu. Not recommended for beginners choose AnacondaPython and ActivePython, in my opinion not as good as they provide convenience to the user the trouble of learning more.

Cpython

  • CPython reference implementation belong Python, Python can be regarded as all other derivative distributions of a standardized version. CPython written in C language, and its authors included a number of core staff Python language's top decision-making levels. CPython in terms of optimizing performance was the most conservative. Of course, this is not a drawback, but the design orientation. Python maintainers who want to build for the Python CPython compatibility with the most widely standardized implementation. CPython most suitable for high compatibility with the conformance requirements of the standard Python users. In addition, CPython want to apply equally to the basic way to use Python and are willing to give up the convenience of some professionals.

Anaconda Python

  • Anaconda Anaconda Company from the hand (formerly known as Continuum Analytics), its design goal is to serve those Python developers need to be provided by a commercial vendor support and have business support services. Anaconda Python's main use cases include mathematics, statistics, engineering, data analysis, machine learning, and other related applications. Anaconda bundled with Python business and science among the various types of common usage scenarios libraries - including SciPy, NumPy and Numba etc., to provide more library access capabilities through a set of customized package management systems.

ActivePython

  • And Anaconda similar, ActivePython same company by the creation and maintenance of --ActiveState-profit enterprises. The company also runs sales multilingual and multi-language Komodo IDE. ActivePython major business-oriented users and data scientists - that want to use the Python language, but do not want to waste a lot of energy in the assembly and management of Python. ActivePython using conventional pip in the Python Package Manager, but speaking also certified compact package to provide hundreds of sets of common libraries, plus the Intel Math Kernel Library and some other public libraries have a third-party dependencies.

PyPy

  • PyPy belonging CPython interpreter alternatives, utilizing time (JIT) compiler to execute the acceleration program Python. According to the actual execution of the task, its performance may be very significant. For the people complaining about the sound Python-- especially CPython, mainly revolves around its speed performance. By default, Python's speed far less than the C language - the gap may even reach several hundred times. PyPy JIT will compile Python code into machine language, leading to an average of 7.7 times the speed of CPython. In certain specific tasks, which can reach 50 times the speed effect.

Jython

  • JVM (Java virtual machine) can as an option in several languages ​​in addition to Java run time. The long list includes Groovy, Scala, Clojure, Kotlin, Python, and - yes, of course, Jython. Jython biggest drawbacks support 2.x version of Python is its only. Currently ability to support Python 3.x version is still in development, but still take quite some time. Moment, there is no relevant version release.

IronPython

  • Jython similar to the JVM Python implementations positioning, IronPython belong when running a .Net based - or CLR (Common Language Runtime) - the Python implementation. IronPython using the CLR the DLR (dynamic language runtime) to allow Python programs to dynamically equivalent to the level achieved CPython operation. And similar Jython, IronPython currently only supports Python 2.x version. But IronPython 3.x implementations already in full swing in development.

Installing Python

When you download from the official website of Python, please pay attention to choose the correct version. If it is for learning, download the latest version is no problem, if it is used in the production, you will have to consider the development needs of third-party modules support the latest version of Python. Do not forget to check the bottom two check boxes during installation, or bring some trouble will follow the module is installed. Recommended default installation.

Conveniently choose a development tool

Learning a programming language, first of all to find a combination of integrated development tools, it seems to be a natural idea. Why not? IDE can automatically filled, can be a key to run, you can breakpoint debugging. Use the IDE development projects, like driving a luxury car interior, enjoy the pleasure of driving is like, who would take care of the inside of the engine hood is how to work it? My younger colleagues are also fans of IDE, originally used pycharm, then is hot nowadays vscode.

However, I have always believed that the programming is like driving, the driver is a programmer, and professional drivers not to drive as colored white-collar Jinling commuter skills. Since it is a professional driver, it can not be satisfied with a bow tie, white gloves driving interior luxury, high-end configuration of the car, but must have the ability to open the engine cover repairs and maintenance.

基于这个观点,我不建议初学者一开始就使用集成开发工具——至少,在开始第一个星期不要使用IDE。对于Python这样一种解释型的脚本语言,一款趁手的编辑器就足够了。Linux平台上,Vim或者Emacs都足够好(如果你通晓二者或者其中之一的话,请接受我的敬意);Windows平台上,我推荐使用notepad++。Python初学者使用编辑器而非IDE的好处是:

  1. 专注于Python本身,而不是被工具使用问题所困扰。君不见,知乎上关于Pycharm和VSCODE的使用说明、常见问题的解决方案,多得几乎超过了讨论Python本身

  2. 手工运行代码,可以更直观、更深刻地了解脚本的解释执行过程

  3. 手工调试代码,有助于代码优化,提高代码把控能力

  4. 可以更好地使用pip安装和管理第三方模块

 

习惯使用IDLE,这是学习Python最好的方式

 

解释型语言的优势,就是可以写一句执行一句,想到哪儿写到哪儿,不必像编译型语言那样得把程序全部写完,编译成功后才能运行。我特别喜欢使用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-100
140

 

小技巧

1. tab键自动补齐

2. 光标移动到执行过的语句上敲击回车,可以重复这个命令

3. 下划线(_)可以获取最后一次执行结果

实际上,IDLE就是一个IDE,你可以用它来创建或打开.py脚本文件,可以编辑、运行和调试。

 

严格遵从编码规范

 

Linux 平台上,一个 python 源码文件应该以下部分组成。Windows 平台上,可以省略第一项。

  1. 解释器声明

  2. 编码格式声明

  3. 模块注释或文档字符串

  4. 模块导入

  5. 常量和全局变量声明

  6. 顶级定义(函数或类定义)

  7. 执行代码

附上一个 demo,仅供参考。更详细的编码规范,请参考拙作《我的 Python 编码规范》。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


"""通常这里是关于本文档的说明(docstring),须以半角的句号、 问号或惊叹号结尾!

本行之前应当空一行,继续完成关于本文档的说明
如果文档说明可以在一行内结束,结尾的三个双引号不需要换行;否则,就要像下面这样
"""


import os, time
import datetime
import math

import numpy as np
import xlrd, xlwt, xlutils

import youth_mongodb
import youth_curl


BASE_PATH = r"d:\YouthGit"
LOG_FILE = u"运行日志.txt"


class GameRoom(object):
    """对局室"""

    def __init__(self, name, limit=100, **kwds):
        """构造函数!

        name        对局室名字
        limit       人数上限
        kwds        参数字典
        """

        pass


def craete_and_start():
    """创建并启动对局室"""

    pass


if __name__ == '__main__':
    # 开启游戏服务
    start()

 

代码的运行、调试

 

如果你使用的集成开发工具,那么代码的运行和调试,就完全依赖于工具了。如果你使用编辑器开写代码,那就需要手工运行和调试代码。运行代码分成两步:

第1步,打开一个命令行窗口,路径切换到脚本所在的文件夹。我习惯在脚本所在窗口的空白位置(确保没有选中任何对象),按下shift键点击鼠标右键,在弹出的菜单中选择打开Powershell窗口。如下图所示。

第2步,输入python+空格+脚本文件名,回车即可运行。输入脚本文件名时,按tab可以自动补齐。脚本的运行信息、错误信息、运行结果等,都可以显示在这个窗口中。这是最原始的信息。你在其他开发工具中看到信息,都是对这些信息的再加工。

手工调试代码的手段不多,除了 print 信息,几乎只有把调试信息写成调试文件了。听起来,好像问题很严重,其实只是理念和取向不同而已。反过来想,手段单一,不恰好意味着简单、简明吗?十几年来,我一直使用 print 调试,坚信没有比它更好的了。

 

模块管理

 

在Python语言的发展过程中,安装和管理第三方模块的方法也历经变化。现在,我们终于等来了pip这个近乎完美的工具。pip除了安装(install)和删除(uninstall)这两大功能,还可以指定模块的安装版本(无需预先删除当前已安装版本),可以显示所有已安装的模块,还可以通过 upgrade 自主升级。

很多同学在使用pip时会遇到各种各样稀奇古怪的问题,我在这里解释一下:

同时安装了py2/py3

同时安装了py2/py3,将会存在多个版本的pip.exe,你如果直接运行:

pip install <模块名>

则有可能因为pip.exe版本不对而出错。正确的做法是指定python版本,-m是python解释器的参数,意思是把pip模块做为脚本运行,完整命令如下:

py -3 -m pip install <模块名>

使用Anaconda,或者通过IDE来安装模块

如果你使用的是Anaconda Python,或者你是通过IDE来安装模块,则需要检查它们的配置和设置,情况各有不同,没有统一的解决方案。

仅安装了py2 或 py3

如果你的计算机只安装了py2 或者 py3,那么上面两种安装方法应该都没有问题。如果你的电脑找不到pip.exe文件,则可以使用这个命令生成:

python -m ensurepip

pip应用演示

下面,就以同时安装了py2/py3的计算机为例(如果只安装了py2或py3,需要将下面演示中的py -3替换成python),演示pip模块的用法。不管任何情况,我都建议使用-m参数调用pip模块,而不是直接使用 pip.exe 安装模块。

# 虽然可以这样使用pip安装模块(以numpy为例)
PS D:\XufiveGit\wxgl> pip install numpy

# 但我建议这样使用pip
PS 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模块,这里是我见过的最全、最稳定的python模块仓库,由加州大学欧文分校荧光动力学实验室创建并维护。

发布自己的模块安装包

如果你的很多个项目中,都会用到你自己的某些模块,那么,把这些模块做成安装包,安装到你的开发环境里,可能是最佳选择。拙作《学习笔记:发布自己的python模块安装包》对此有详细说明(https://blog.csdn.net/xufive/article/details/88640229)。

版权声明:本文为CSDN博主「天元浪子」的原创文章。

发布了65 篇原创文章 · 获赞 0 · 访问量 569

Guess you like

Origin blog.csdn.net/weixin_46089319/article/details/103956295