To Python beginners

Tianyuan prodigal son 2020-11-13 09:05:59
python beginners


1. Preface

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 .

2. Clear learning objectives , Don't rush for success , Not so ambitious

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 .
 Insert picture description here 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 .
 Insert picture description here 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 .

3. Starting to learn Python Before , You need to do some preparation

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 .

2.1 Python The various distributions of

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

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 Python

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 .

ActivePython

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

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 .

Jython

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 .

IronPython

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 .

2.2 install Python

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 .
 Insert picture description here

2.3 Choose a handy development tool

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 :

  1. Focus on python In itself , Instead of being bothered by tool use problems . Have you noticed , Know more about pycharm and vscode Instructions for use 、 Solutions to common problems , More than discussion python In itself
  2. Run code manually , Can be more intuitive 、 Better understanding of script interpretation and execution process
  3. Manual debugging code , Help code optimization , Improve code control ability
  4. It can be used better pip Install and manage third party modules

3. Habitual use IDLE, This is learning. python The best way

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

Tips

  1. tab Key auto complement
  2. Move the cursor over the executed statement and hit enter , You can repeat this command
  3. 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 .

 Insert picture description here

4. Strictly follow the coding specification

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 .

  1. The interpreter declares
  2. Code format statement
  3. Module comments or document strings
  4. Module import
  5. Constant and global variable declarations
  6. Top level definition ( Function or class definition )
  7. Execute code

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

5. Code running 、 debugging

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 .
 Insert picture description here
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 .
 Insert picture description here
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 .

5. Module management

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 :

5.1 At the same time installed py2/py3

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 >

5.2 Use Anaconda, Or by IDE To install the module

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 .

5.3 Only installed py2 or py3

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

5.4 pip Application demonstration

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

5.5 Module warehouse

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 .

5.4 Release your own module installation package

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 .

Postscript

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 .

 Insert picture description here

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 ”.

 Insert picture description here

版权声明
本文为[Tianyuan prodigal son]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database