Welcome to “Python Advanced ” special column ！ Every student who comes here , I should have learned a lot Python Basic knowledge of , In the process of trying to grow . in the meantime , There must have been a lot of confusion , I feel confused about the future direction of learning . I fully understand the situation you are facing . I started from 2007 Contact began in python This programming language , from 2009 Single use began in python Deal with all the development work , Until today, . Review your learning process , I have encountered countless difficulties , I have been confused 、 Confused . Start this column , It's to help people as confused as I was Python Beginners out of trouble 、 The rapid growth . I hope my experience can really help you .
Now it's a hustle and bustle 、 Impetuous times . We are always attracted by the hot spots in our life , There is little time and opportunity for deep reading and thinking . I always thought , Learning needs to sink in and study slowly , It's long term. ; meanwhile , Learning should not be given too much utilitarian color . One Python A programmer's growth roadmap should look like this ： Basic grammar –> Language sense training –> Project practice –> Continue learning in different directions –> Intermediate programmer –> Expand depth and breadth –> Senior programmer .
However , Many novices have a learning roadmap like this ： After learning the basic grammar , Don't understand http The protocol and Ajax Asynchronous requests , So he went to study reptiles ; perhaps , After learning basic grammar , I'm going to do visual recognition , even OpenCV We can't understand the data structure of ; even to the extent that , After learning basic grammar, we will study neural network directly , It turned out to be a replay, from entry to abandonment .
My advice for beginners is , Don't rush for success , Not so ambitious , Step-by-step , Slowly but surely , It's natural that you work hard . Don't rush for success , Avoid detours , Not only will it not slow you down , It will save you time . Not so ambitious , Achieve a goal , Set the next goal , In continuous success and progress , Build self-confidence , Stimulate a stronger interest in learning .
Now is better than never,
Although never is often better than *right* now.
This is a Python It's a sentence in Zen , The translation means , It may be better to do than not to , But it's better not to do it without thinking about it . You bet , Starting to learn Python Before , Some background you need to know , Make some choices , And get ready on your computer .
Python It's uncle GUI's only son , But he had a lot of cousins , There are several famous ones . If you're not sure which is more friendly to you , I suggest you choose your own Python—— Even if you need to deal with other cousins in the future , It's also familiar . It is not recommended that beginners choose AnacondaPython and ActivePython, In my opinion, the convenience they provide is not as much as the trouble they bring to users learning .
CPython Belong to Python Refer to the implementation scheme , It's all the other Python A set of standardized versions of a derivative distribution .CPython utilize C Written in language , And it's written by many people Python The core people in the top decision-making level of language .CPython The most conservative in terms of optimization . Of course , This is not a disadvantage , It's design orientation .Python The defenders of hope will CPython Make it Python The most widely compatible and standardized implementation scheme .CPython Best for Python Users with high requirements for compatibility and consistency of standards . Besides ,CPython The same applies to wanting to use in the most basic way Python Professionals who are willing to give up some convenience for this .
Anaconda Derived from Anaconda The hands of the company ( It was originally called Continuum Analytics), It is designed to serve those who need to be supported by commercial suppliers and have enterprise support services Python developer .Anaconda Python The main use cases for are math 、 statistical 、 engineering 、 Data analysis 、 Machine learning and other related applications .Anaconda It's bound with Python Common libraries in commercial and scientific use scenarios —— Include SciPy、NumPy as well as Numba wait , At the same time through a set of customized software package management system to provide more library access .
And Anaconda similar ,ActivePython It is also created and maintained by for-profit enterprises ——ActiveState company . The company also sells multilingual runtimes and multilingual Komodo IDE.ActivePython Mainly for enterprise users and data scientists —— I want to use Python Language , But I don't want to waste a lot of energy on Python In terms of assembly and management .ActivePython Use Python In the conventional pip Package manager , But it also provides hundreds of general libraries in the form of certified compression packages , In addition, Intel math core library and other public libraries with third-party dependency relationship .
PyPy Belong to CPython An alternative to the interpreter , Its use is immediate (JIT) Compile to speed up Python Execution of procedures . According to the actual implementation of the task , The performance improvement can be very significant . People for Python—— especially CPython The voice of complaint , Mainly around its speed performance . By default ,Python It's not as fast as C Language —— The gap can even be hundreds of times .PyPy JIT take Python Code compiled into machine language , And that brings average 7.7 Twice as much as CPython Running speed of . In some specific tasks , Its acceleration effect can reach 50 times .
JVM(Java virtual machine ) Can be used as a division of Java Run time options for multiple languages . This long list includes Groovy、Scala、Clojure、Kotlin、Python as well as —— you 're right , Of course, Jython .Jython The biggest drawback is that it only supports Python Of 2.x edition . At present Python 3.x Version support is still under development , But it's going to take quite a while . The present , No relevant version has been released yet .
Be similar to Jython Of JVM On Python Realize the positioning of the scheme ,IronPython Belong to a set of footholds .Net Runtime —— perhaps CLR( Common language runtime )—— Of Python Implementation scheme .IronPython utilize CLR Of DLR( Dynamic language runtime ) With permission Python Program is equivalent to CPython The dynamic level of the implementation of the operation . And Jython similar ,IronPython Currently only supported Python 2.x edition . however IronPython 3.x The implementation scheme has been in the process of intensive development .
from Python When downloading from the official website , Please pay attention to choose the correct version . If it's for learning , There's no problem downloading the latest version , If it is used for production , Consider whether the third-party modules you need to develop support the latest version of Python. Don't forget to check the bottom two check boxes when installing , Otherwise, it will bring some trouble to the follow-up module installation . It is recommended to install by default .
Learn a programming language , First of all, find a common integrated development tool , It seems to be a natural thought . Why not? ？IDE It can be supplemented automatically , It can be run at one click , You can also debug breakpoints . Use IDE Development projects , It's like driving a luxury car , Just enjoy driving , Who cares how the engine works inside the hood ？ My young colleagues are all IDE The fans of , First use pycharm, And then it was hot vscode.
But , I always thought , Programming is like driving , Programmers are drivers , And a professional driver , It's not white collar workers who regard driving as a commuter skill . As a professional driver , You can't be content with a bow tie 、 Driving with white gloves and luxurious interior 、 Equipped with high-end cars , It must have the ability to open the engine cover for repair and maintenance .
Based on this point of view , I don't recommend that beginners start with integrated development tools —— At least , Don't use... In the first week IDE. about python Such an interpretive scripting language , A handy editor is enough .linux On the platform ,vim perhaps emacs It's good enough （ If you know both or one of them , Please accept my respect ）;windows On the platform , I recommend using notepad++.python Beginners use editors instead of IDE Are the benefits of ：
The advantages of interpretive language , You can write a sentence and execute a sentence , Where to think and where to write , You don't have to write everything like a compiled language , It can only be run after the compilation is successful . I particularly like to use python Of IDLE, Even use it as a calculator . A lot of times , I use IDLE Verify that the code is written correctly , Check whether the module is successfully installed and the version number .IDLE Support tab Key auto complement , I often use this function to view the methods and properties of an object .
>>> import numpy as np >>> np.__version__ '1.17.0' >>> np.hypot(3,4) 5.0 >>> def factorial(n): # Calculation n The factorial if n == 0: # Recursive export return 1 return n*factorial(n-1) # Call itself close to the exit of the recursion >>> factorial(5) 120 >>> _*2-100 140
- tab Key auto complement
- Move the cursor over the executed statement and hit enter , You can repeat this command
- Underline (_) You can get the last execution result
actually ,IDLE It's just one. IDE, You can use it to create or open .py Script files , Can edit 、 Operation and commissioning .
Linux On the platform , One python The source code file should consist of the following parts .Windows On the platform , The first item can be omitted .
Attach a demo, For reference only . More detailed coding specifications , Please refer to my book 《 my Python Coding standards 》.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usually here is a description of this document （docstring）, Half a full stop 、 At the end of a question mark or exclamation point ! There should be a blank line before this line , Continue to complete the instructions for this document If the document description can end in one line , The last three double quotes don't need to wrap ; otherwise , Just like this """ 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" Run log .txt" class GameRoom(object): """ Against the office """ def __init__(self, name, limit=100, **kwds): """ Constructors ! name The name of the office limit The maximum number of people kwds Parameter Dictionary """ pass def craete_and_start(): """ Create and start the matchmaking room """ pass if __name__ == '__main__': # Open the game service start()
If you use an integrated development tool , So code running and debugging , It's totally dependent on tools . If you use an editor to write code , You need to run and debug the code manually . Running the code is divided into two steps ：
The first 1 Step , Open a command line window , Path to the folder where the script is located . I used to be in the blank space of the script window （ Make sure no objects are selected ）, Press down shift Click the right mouse button , Select open in the pop-up menu Powershell window . As shown in the figure below .
The first 2 Step , Input python+ Space + Script name , Press enter to run . When you enter the script file name , Press tab It can be supplemented automatically . The running information of the script 、 error message 、 Running results, etc , Can be displayed in this window . This is the most primitive information . You see information in other development tools , It's all about reprocessing this information .
Of course , Many editors also support custom run commands , It can run with one key python Script . With Notdpan++ For example , Click on “ function ”->“ function ” menu , Enter... In the pop-up window ：
cmd /k cd /d “$(CURRENT_DIRECTORY)” & python “$(FULL_CURRENT_PATH)” & echo. & pause & exit
Because of the escape , Copy the command , Please check $ Whether there is \ Symbol , if there be , Please delete . Next , Click on “ preservation ” Button , Enter the name of the new command in the pop-up window , such as PyRun, Define shortcut keys , Finally, click “ determine ” Button .
After completing the above settings , You can go to Notepad++ Use menu commands or shortcut keys to run Python Code. .
There are not many ways to debug code manually , except print Information , Almost only debugging information is written as debugging files . Sound , It seems that the problem is serious , In fact, it's just different ideas and orientations . In turn to , The means are single , It doesn't just mean simple 、 Is it concise ？ For more than a decade , I always use print debugging , Believe that there is nothing better than it .
stay python In the development of language , The way you install and manage third-party modules has also changed . Now? , We are finally waiting for pip This almost perfect tool .pip In addition to installation （install） And delete （uninstall） These two functions , You can also specify the installed version of the module （ There is no need to pre delete the currently installed version ）, All installed modules can be displayed , You can also use upgrade Self upgrade .
Many students are using it pip You will encounter all kinds of strange problems , I'll explain it here ：
At the same time installed py2/py3, There will be multiple versions of pip.exe, If you run directly ：
pip install < Module name >
It may be because pip.exe Wrong version and error . The right thing to do is to specify python edition ,-m yes python Interpreter parameters , Meaning is to put the pip Modules run as scripts , The complete command is as follows ：
py -3 -m pip install < Module name >
If you're using Anaconda Python, Or you do it through IDE To install the module , You need to check their configuration and settings , The situation is different , There is no unified solution .
If your computer only has py2 perhaps py3, There should be no problem with both of the above installation methods . If your computer can't find pip.exe file , You can use this command to generate ：
python -m ensurepip
below , At the same time py2/py3 For example, the computer of （ If only installed py2 or py3, You need to put the py -3 Replace with python）, demonstration pip Usage of modules . No matter what , I recommend using -m Parameter call pip modular , Instead of using it directly pip.exe Install the module .
# Although it can be used in this way pip Install the module （ With numpy For example ） PS D:\XufiveGit\wxgl> pip install numpy # But I suggest that you use pip PS D:\XufiveGit\wxgl> py -3 -m pip install numpy # Delete module PS D:\XufiveGit\wxgl> py -3 -m pip uninstall numpy # Install the module , Specify the version PS D:\XufiveGit\wxgl> py -3 -m pip install numpy=1.15.0 # Self upgrade PS D:\XufiveGit\wxgl> py -3 -m pip install --upgrade pip # Show installed modules 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 Also used to install local whl file ：
PS D:\PyPackage\py3> py -3 -m pip install .\basemap-1.2.0-cp37-cp37m-win_amd64.whl
If you need to download python modular , This is the most complete I've ever seen 、 The most stable python Module warehouse , Created and maintained by the fluorescence kinetics laboratory at the University of California, Irvine .
If you have many projects , You'll use some of your own modules , that , Make these modules into installation packages , Install into your development environment , Maybe the best choice . My work 《 Learning notes ： Publish your own python Module installation package 》 There is a detailed description of this .
Recently, a lot of friends have consulted through private letters about Python Learning problems . To facilitate communication , I am here CSDN Of app Created on “Python Homework guidance ” stronghold , oriented Python beginner , Provide consulting services for you 、 Coach Python Homework . Welcome interested students to use wechat code scanning to join .
From blogs to official account , Every article 、 Every question 、 Every sentence 、 Every line of code , All insist on originality , Never copy , This is my principle . If you like , Please pay attention to my WeChat official account “Python Homework counselor ”.