python beginner

Clear learning objectives, not anxious

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 is long

At the same time, learning should not be given too much utilitarian; period. A Python programmer's growth roadmap should be like this: basic grammar -> Language Sense Training -> topic Exercise -> points the direction to continue learning -> intermediate programmers ->

Expand the depth and breadth -> advanced programmers.

However, many novice learning road map is like this: After learning basic grammar, do not understand http protocol and Ajax asynchronous requests, 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 experience and advice is, do 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 of Better Within last Never, 
Although is Never IS Often field of Better Within last * right * now. 
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 the Queen of Python-- even your future needs and his other cousin

Brother deal, 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 top-level decision-making Python language 
core staff layer. 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 pressure
reduction package in the form of hundreds of sets of providing universal library, plus Intel Math Kernel libraries 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. Python-- especially for people CPython 
sound complain, 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
in CPython speed. 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

 Python 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 later

It 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, you can not

Satisfied with 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.

Based on this view, I do not recommend beginners to start using integrated development tools - at least, do not use the IDE at the beginning of the first week. For python such an interpreted scripting language, a conveniently editor on foot

enough. linux platform, vim or emacs are good enough (or both if you are familiar with one of them, please accept my respect); on the windows platform, I recommend using notepad ++. python beginners knitting

Benefits editor rather than IDE are:

1, focusing on python itself, instead of being plagued by the use of tools. Do not you see, know and instructions on pycharm vscode on peace, solutions to common problems, little more than a discussion of python itself almost
2, run the code by hand, can be more intuitive, more profound understanding of the interpretation of the script execution
3, manual debugging code, code optimization can help to improve the ability to control the code
4, better use pip install and manage third-party modules

Accustomed to using IDLE, this is the best way to learn python

Advantages of interpreted languages ​​is that you can write an implementation of one, think of where to where to write to, do not have to finish all the procedures as like a compiled language, compiled to run successfully. I especially like the use of python IDLE

And even use it as a calculator. Many times, I used the wording IDLE verification code is correct, to see whether the module is successfully installed and version number. IDLE support tab completion, I often use this feature to view an object

The methods and properties.

>>> Import numpy AS NP
 >>> NP. __VERSION__ 
' 1.17.0 ' 
>>> np.hypot (3,4- )
 5.0 
>>> DEF factorial (n): # calculate the factorial of n 
    IF n == 0: # recursive outlet 
        return . 1
     return n-factorial * (. 1-n-) # close the outlet direction calls itself recursively
 
>>> factorial (. 5 )
 120 
>>> _ * 2-100 
140

Tips

  • tab completion
  • Move the cursor to the pressing the return statement is executed, the command may be repeated
  • An underscore (_) can obtain the results of the last execution

In fact, IDLE is a IDE, you can use it to create or open a .py script file, you can edit, run, and debug.

 Strict compliance with coding standards

  On the Linux platform, a python source code file should be the following parts. On the Windows platform, you can omit the first term.

  • Interpreter declaration
  • Encoding format statement
  • Module comment or docstring
  • Import module
  • Constants and global variable declaration
  • Top defined (class definition or function)
  • Code execution

 

好在龟叔说过,A Foolish Consistency is the Hobgoblin of Little Minds(尽信书,不如无书),只要保持一致性、可读性,就是一个好的规范。基于PEP8规范的原则

结合开发团队在工作中的养成的习惯,我整理了一份实用的编码规范,推荐给初学者。

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()

编码格式声明

通常,编码格式声明是必需的。如果 python 源码文件没有声明编码格式,python 解释器会默认使用 ASCII 编码,一旦源码文件包含非ASCII编码的字符,python 解释器

就会报错。以 UTF-8 为例,以下两种编码格式声明都是合乎规则的。

# -*- coding: utf-8 -*-
# coding = utf-8

我一直 UTF-8 编码格式,喜欢使用第一种声明方式。

Windows 平台上,编码格式声明必须位于 python 文件的第一行。Linux 平台上,编码格式声明通常位于 python 文件的第二行,第一行是 python 解释器的路径声明。

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

 缩进

统一使用 4 个空格进行缩进。绝对不要用tab, 也不要tab和空格混用。对于行连接的情况,我一般使用4空格的悬挂式缩进。例如:

var_dict = {
'name': 'xufive',
'mail': '[email protected]'
} 

引号

引号使用的一般性原则:

  • 自然语言使用双引号
  • 机器标识使用单引号
  • 正则表达式使用双引号
  • 文档字符串 (docstring) 使用三个双引号

注释

#号后空一格,段落件用空行分开(同样需要#号):

# 块注释
# 块注释
#
# 块注释
# 块注释

行内注释,至少使用两个空格和语句分开:

age += 1 # 年龄增加一岁

比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性:

server= gogame(room, options)

# =====================================
# 请勿在此处倾倒垃圾!!!
# =====================================

if __name__ == '__main__':
server.run()

 空行

空行使用的一般性原则:

  • 编码格式声明、模块导入、常量和全局变量声明、顶级定义和执行代码之间空两行
  • 顶级定义之间空两行,方法定义之间空一行
  • 在函数或方法内部,可以在必要的地方空一行以增强节奏感,但应避免连续空行

空格

空格使用的一般性原则:

  • 在二元运算符两边各空一格,算术操作符两边的空格可灵活使用,但两侧务必要保持一致
  • 不要在逗号、分号、冒号前面加空格,但应该在它们后面加(除非在行尾)
  • 函数的参数列表中,逗号之后要有空格
  • 函数的参数列表中,默认值等号两边不要添加空格
  • 左括号之后,右括号之前不要加添加空格
  • 参数列表, 索引或切片的左括号前不应加空格

文档字符串

文档字符串是包、模块、类或函数里的第一个语句。这些字符串可以通过对象的__doc__成员被自动提取,并且被pydoc所用。文档字符串的使用三重双引号(""")。

如果文档字符串内容不能在一行内写完,首行须以句号、 问号或惊叹号结尾,接一空行,结束的三重双引号必须独占一行。

导入模块

导入总应该放在文件顶部,位于模块注释和文档字符串之后,模块全局变量和常量之前。导入应该按照从最通用到最不通用的顺序分组,分组之间空一行:

  • 标准库导入
  • 第三方库导入
  • 应用程序指定导入

应当避免使用以下的导入方法:

from math import *

命名规范

命名建议遵循的一般性原则:

  • 模块尽量使用小写命名,首字母保持小写,尽量不要用下划线
  • 类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头
  • 函数名一律小写,如有多个单词,用下划线隔开
  • 私有函数可用一个下划线开头
  • 变量名尽量小写, 如有多个单词,用下划线隔开
  • 常量采用全大写,如有多个单词,使用下划线隔开

代码的运行、调试

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

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

出的菜单中选择打开Powershell窗口。如下图所示。

 

 

 

第2步:输入python+空格+脚本文件名,回车即可运行。输入脚本文件名时,按tab可以自动补齐。脚本的运行信息、错误信息、运行结果等,都可以显示在这个窗口中

这是最原始的信息。你在其他开发工具中看到信息,都是对这些信息的再加工。

当然,很多编辑器也支持自定义运行命令,可以实现一键运行python脚本。以Notdpan++为例,点击“运行”->“运行”菜单,在弹出的窗口中输入:

cmd /k cd /d “$(CURRENT_DIRECTORY)” & python “$(FULL_CURRENT_PATH)” & echo. & pause & exit

因为转义缘故,复制该命令的话,请检查$符号前面是否有\符号,如有,请删除。接下来,点击“保存”按钮,在弹出的窗口中输入新增命令的名称,比如PyRun,定义快捷

键,最后点击“确定”按钮。

完成以上设置后,就可以在Notepad++中使用菜单命令或者快捷键运行Python代码了。手工调试代码的手段不多,除了 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为例)
D:\XufiveGit\wxgl> pip install numpy

# 但我建议这样使用pip
D:\XufiveGit\wxgl> py -3 -m pip install numpy

# 删除模块
D:\XufiveGit\wxgl> py -3 -m pip uninstall numpy

# 安装模块,指定版本
D:\XufiveGit\wxgl> py -3 -m pip install numpy=1.15.0 # 自主升级 D:\XufiveGit\wxgl> py -3 -m pip install --upgrade pip # 显示已安装的模块 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文件:

D:\PyPackage\py3> py -3 -m pip install .\basemap-1.2.0-cp37-cp37m-win_amd64.whl

模块仓库

如果你需要下载python模块,这里是我见过的最全、最稳定的python模块仓库,由加州大学欧文分校荧光动力学实验室创建并维护。

Python模块仓库:https://www.lfd.uci.edu/~gohlke/pythonlibs/

模块安装包

如果你的很多个项目中,都会用到你自己的某些模块,那么,把这些模块做成安装包,安装到你的开发环境里,可能是最佳选择。

发布自己的python模块安装包,首先得把自己的模块做成 .whl 格式的文件,然后再找个地儿存放它,接下来就是在 pip 命令中使用 -i 参数指定这个地儿(下载源)。

Just so sooooooooo

准备工作

注册 pypi.org 用户
我原本就是 pypi 的注册用户,但当我上传 .whl 格式的文件时,却被提示无权限。仔细阅读相关文档才发现,还需要在https://test.pypi.org/account/register/ 注册。

我不确定是不是仅在这里注册就可用了。

使用 pip 安装或升级几个必备工具
生成和上传 .whl 格式的文件需要几个特殊工具,好在这几个工具使用 pip 就可以轻松搞定。

py -3 -m pip install --user --upgrade setuptools wheel 
py -3 -m pip install --user --upgrade twine

规划文件目录
假定要发布的模块名称为 wxgl,包含 scene.py, region.py, colorbar.py 等三个文件。文件目录结构如下:

/wxgl_pkg
 wxgl
    __init__.py
    colorbar.py
    region.py
    scene.py
 README.md
 setup.py

init.py

该文件其内容可以为空。我的 init.py文件如下:

-*- coding: utf-8 -*-

name = 'wxgl'
version = "0.3.0"
version_info = (0, 3, 0, 0)

README.md
关于安装和使用的说明,文本文件,不能使用中文。

setup.py

# -*- coding: utf-8 -*-
import setuptools

with open("README.md", "r") as fh:
long_description = fh.read()

setuptools.setup(
name="wxgl",
version="0.3.0",
author="xufive",
author_email="[email protected]",
description="A 3d library based pyOpenGL.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/xufie/wxgl",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
  ],
)

提醒一点:License 很重要,pipy 检查很严格,不可乱写。最初是我使用 GPL,检查失败,后改用 MIT 才通过。

To build the installation file
to run setup.py script generates installation package file

py -3 setup.py sdist bdist_wheel

Hopefully, you can see the dist folder:

/wxgl_pkg
  dist
    wxgl-0.3.0-py3-none-any.whl
    wxgl-0.0.1.tar.gz
    wxgl
  __init__.py
    colorbar.py
    region.py
    scene.py
  README.md
  setup.py

If you only need .whl file, run:

py -3 setup.py bdist_wheel

Upload installation package file
is switched to the path dist, run:

py -3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*

When prompted to enter a user name, password, wait a moment to complete.

Installation
using the -i parameter, specify the installation source https://test.pypi.org/simple/, other parameters are unchanged:

py -3 -m pip install -i https://test.pypi.org/simple/ wxgl

 

Guess you like

Origin www.cnblogs.com/yangmaosen/p/Mr_Y4.html