Home  >  Article  >  Backend Development  >  Detailed introduction to the development origin and basic knowledge of Python

Detailed introduction to the development origin and basic knowledge of Python

PHP中文网
PHP中文网Original
2017-06-22 13:40:193026browse

1. Introduction to the development of Python

1. Introduction to the author of Python

The author of Python, Guido von Rossum, Dutch. In 1982, Guido received a master's degree in mathematics and computing from the University of Amsterdam. In 1989, he founded the Python language. At that time, he was still at CWI (Centrum voor Wiskunde en Informatica, National Institute of Mathematics and Computer Science) in the Netherlands. In early 1991, Python released its first public release. Guido originally lived in the Netherlands, moved to the United States in 1995, and met his current wife. In early 2003, Guido and his family, including his son Orlijn, born in 2001, were living in the suburbs of Northern Virginia, Washington.

 
In 2002, at the European Conference of Free and Open Source Software Developers held in Brussels, Belgium, Guido van Rossum received the 2001 Free Software Progress Award from the Free Software Foundation.
In May 2003, Guido won the Dutch UNIX Users Group Award.
In 2006, he was recognized as a famous engineer by the Association for Computing Machinery (ACM).
In December 2005, Guido van Rossum joined Google. He wrote a web-oriented code browsing tool for Google in Python. There he spent half his time maintaining Python development.
On December 7, 2012, Dropbox announced that Guido van Rossum had joined Dropbox.
2. Introduction to Python development

 In 1989, in order to pass the Christmas vacation, Guido began to write a compiler for the Python language. The name Python comes from Guido’s beloved TV series Monty Python’s Flying Circus. He hopes that this new language called Python can meet his ideal: to create a language between C and shell that is comprehensive, easy to learn, easy to use, and scalable.
 In 1991, the first Python compiler was born. It is implemented in C language and can call C language library files. From its birth, Python has had: classes, functions, exception handling, core data types including tables and dictionaries, and a module-based expansion system.
 1999年,Granddaddy of Python web frameworks, Zope 1 was released in 1999
  1994年,Python 1.0 - January 1994 Added lambda, map, filter and reduce .
 In 2000, Python 2.0 - October 16, 2000, a memory recycling mechanism was added, forming the basis of the current Python language framework
 2004, Python 2.4 - November 30, 2004, the same year that the most popular WEB framework Django was born
 2006年,Python 2.5 - September 19, 2006
 2008年,Python 2.6 - October 1 , 2008
 2010年,Python 2.7 - July 3, 2010
 2014年,In November 2014, it was announced that Python 2.7 would be supported until 2020, and reaffirmed that there would be no 2.8 release as users were expected to move to Python 3.4+ as soon as possible
 2008年,Python 3.0 - December 3, 2008
 2009年,Python 3.1 - June 27, 2009
 2011年,Python 3.2 - February 20, 2011
 2012年,Python 3.3 - September 29, 2012
 2014年,Python 3.4 - March 16, 2014
 2015年,Python 3.5 - September 13, 2015

 2015年 , Python 3.5.1, documentation released on 07 December 2015.

 2016年,Python 3.5.2, documentation released on 27 June 2016.

 2016 Year, Python 3.6.0, documentation released on 23 December 2016.

 2017年, Python 3.6.1, documentation released on 21 March 2017.

Refer to the official documentation:

Users who read it carefully will definitely find out why Python 3.0 was released in 2008, and why Python 2.7 was released in 2010. This is because Python 3.0 was released at that time. When it was released, it no longer supported the Python 2.0 version, which caused many users to be unable to upgrade to the new version normally. Therefore, a transitional version of Python 2.7 was later released, and Python 2.7 will be supported until 2020, so novices should start from Python 3. .0 Get it now.

2. Current main application areas of Python:

  • Cloud computing: Cloud computing is the most The language of fire, typical application OpenStack

  • ##WEB Development: Many excellent WEB frameworks, many large websites are developed in Python, Youtube, Dropbox, Douban. . . , Typical WEB frameworks include Django

  • ##Scientific operations, artificial intelligence

    : Typical libraries NumPy, SciPy, Matplotlib, Enthought libraries,pandas

  • System Operation and Maintenance

    : Essential language for operation and maintenance personnel

  • Finance

    : quantitative trading, financial analysis, in the field of financial engineering , Python is not only used, but also used the most, and its importance is increasing year by year. Reason: As a dynamic language, Python has a clear and simple language structure, rich libraries, mature and stable, scientific calculation and statistical analysis are very good, the production efficiency is much higher than c, c++, java, especially good at strategy backtesting

  • Graphic GUI

    : PyQT, WxPython,TkInter

3. Application of Python in some companies:

    Google: Google App Engine, code.google.com, Google earth, Google crawler, Google advertising and other projects are all using Python extensively Development
  • CIA: The CIA website is developed in Python
  • NASA: The National Aeronautics and Space Administration (NASA) uses Python extensively for data analysis and Operation
  • YouTube: The world’s largest video website YouTube is developed in Python
  • Dropbox: The largest online cloud storage website in the United States, all Implemented in Python, the website handles the upload and download of 1 billion files every day
  • Instagram: The largest photo sharing social networking site in the United States, more than 30 million photos are shared every day, all using python Development
  • Facebook: A large number of basic libraries are implemented in Python
  • Redhat: The yum package in the world's most popular Linux distribution The management tool is developed using python
  • Douban: Almost all the company’s business is developed through Python
  • Zhihu: The largest in China Question and answer community, developed through Python (foreign Quora)
  • Chunyu Doctor: The well-known domestic online medical websites are developed in Python

  • In addition to the above, there are also Sohu, Kingsoft, Tencent, Shanda, NetEase, Baidu, Alibaba, Taobao, Tudou, Sina, Guoke and other companies are using Python to complete a variety of tasks.

4. What kind of programming language is Python

Programming languages ​​are mainly from the following perspectives: Classify, compiled and interpreted, static language and dynamic language, strongly typed definition language and weakly typed definition language, what does each classification mean? Let’s take a look. .

What is the difference between compilation and interpretation?

Compiler compiles each statement of the source program into machine language and saves it as a binary file, so that the computer can directly Machine language is used to run this program, and the speed is very fast;

And the interpreter only interprets the program one by one into machine language for the computer to execute, so the running speed is It is not as fast as the compiled program.

This is because the computer cannot directly recognize and execute the statements we write, it can only recognize machine language (in binary form)

Compiled vs Interpreted

Compiled
Advantages: Compilers generally have a pre-compilation process to compile the code optimization. Because compilation is only done once and does not require compilation at runtime, compiled language programs have high execution efficiency. Can run independently of the locale.
Disadvantages: If you need to modify it after compilation, you need to recompile the entire module. When compiling, machine code is generated according to the corresponding operating environment. There will be problems when transplanting between different operating systems. Different executable files need to be compiled according to the running operating system environment.

Interpreted
Advantages: It has good platform compatibility and can run in any environment, provided that an interpreter (virtual machine) is installed. Flexible, you can modify it directly when modifying the code, and it can be deployed quickly without downtime for maintenance.

Disadvantages: It needs to be explained every time it is run, and the performance is not as good as compiled languages.

Python is a dynamically interpreted, strongly typed definition language.

5. Advantages and Disadvantages of Python
Let’s look at the advantages first:
1. Python’s positioning is “elegant”, “clear” and “simple”, so Python programs always seem simple and easy to understand. Beginners learning Python are not only easy to get started, but also can write very, very complex programs if they go deeper in the future.
2. The development efficiency is very high. Python has a very powerful third-party library. Basically, if you want to realize any function through the computer, the official Python library has corresponding modules to support it. After downloading and calling directly, in the basic library Develop based on the basics, greatly reducing the development cycle and avoiding reinventing the wheel.
3. High-level language - When you write a program in Python, you don't need to think about low-level details such as how to manage the memory used by your program.
4. Portability - Due to its open source nature, Python has been ported to many platforms (with modifications to enable it to work on different platforms). If you are careful to avoid using system-dependent features, your Python program will run without modification on almost any system platform on the market.
5. Scalability - If you need a critical piece of code to run faster or want certain algorithms not to be public, you can write part of your program in C or C++, and then use it in your Python program Use them.
6. Embeddability - You can embed Python into your C/C++ program to provide scripting functionality to your program users.
Let’s look at the shortcomings:
1. Slow speed. Python’s running speed is indeed much slower than C language, and it is also slower than Java. Therefore, this is the main reason why many so-called experts disdain to use Python. The reason, but in fact, the slow running speed referred to here cannot be directly perceived by users in most cases, and must be reflected with the help of testing tools!
2. The code cannot be encrypted because Python is an interpreted language and its source code is stored in plain text. However, I don’t think this is a disadvantage. If your project source code must be encrypted, then you It shouldn't be implemented in Python in the first place.
3. Threads cannot utilize multiple CPUs. This is one of the most criticized shortcomings of Python. GIL, the Global Interpreter Lock, is a tool used by computer programming language interpreters to synchronize threads, making any Only one thread is executing at a time, and Python's thread is the native thread of the operating system. It is pthread on Linux and Win thread on Windows. The execution of the thread is completely scheduled by the operating system. A Python interpreter process has a main line and multiple execution threads of user programs. Even on multi-core CPU platforms, parallel execution of threads is prohibited due to the existence of GIL. Regarding the compromise solution to this problem, we will discuss it in detail in the thread and process chapters later.

6. Python interpreter

When we write Python code, what we get is a .py extension that contains Python code name of the text file. To run the code, you need the Python interpreter to execute the .py file.

Since the entire Python language is open source from specification to interpreter, in theory, as long as the level is high enough, anyone can write a Python interpreter to execute Python code (of course it is very difficult). In fact, multiple Python interpreters do exist.

CPython
After officially downloading and installing Python2.7, we directly obtained an official version of the interpreter: CPython. This interpreter is developed in C language, so it is called CPython.
CPython is the most widely used Python interpreter. By default, all our code is also executed under CPython.


IPython is an interactive interpreter based on CPython. That is to say, IPython is only enhanced in the interactive mode, but the function of executing Python code is completely the same as that of CPython. the same. For example, although many domestic browsers have different appearances, their cores actually call IE.

CPython uses >>> as the prompt, while IPython uses In [serial number]: as the prompt.

PyPy It is said to be the future of Python, and developers also say they want your Python code blocks to use this interpreter.
PyPy is another Python interpreter that targets execution speed. PyPy uses JIT technology to dynamically compile (note not interpret) Python code, so it can significantly improve the execution speed of Python code.
Most Python codes can be run under PyPy, but there are some differences between PyPy and CPython, which results in the same Python code executing under the two interpreters may have different results. If your code is to be executed under PyPy, you need to understand the differences between PyPy and CPython.

Jython
Jython is a Python interpreter running on the Java platform. It can directly compile Python code into Java bytecode for execution.

IronPython
IronPython is similar to Jython, except that IronPython is a Python interpreter running on the Microsoft .Net platform and can directly compile Python code into .Net bytecode .

Summary: There are many Python interpreters, but the most widely used one is CPython. If you want to interact with the Java or .Net platform, the best way is not to use Jython or IronPython, but to interact through network calls to ensure the independence of each program.

7. Use Python2 or Python3

The official recommendation is to upgrade to Python3 as soon as possible, and Python3 has many new functions and features, so Unless some business is written in Python2, it is generally recommended to use Python3.

Python3.0 still has a relatively large function that has not been completed, and that is Twisted. This is a very large system project. It is expected to be completed soon, so stay tuned!

8. Python installation

windows

1. Download the installation package

2. Installation
The latest version of win7 and later systems, the default installation path: C:\Users\Administrator\AppData\Local\Programs\Python\Python36\
3. Configure environment variables
[Right-click computer]--"[Properties ]--》[Advanced System Settings]--》[Advanced]--》[Environment Variables]--》[Find the line with the variable name Path in the second content box and double-click] --> [Python Installation The directory is appended to the variable value, separated by;
For example: the original value;C:\Users\Administrator\AppData\Local\Programs\Python\Python36\, remember to have a semicolon in front

linux, Mac

No installation required, original Python environment, just update the version!

9. Variable/Character Encoding

What are variables?

Simply put, a variable is a label used to describe the space address in memory. The process of declaring variables is the process of applying for a space in memory to store data.

Declare variables


#_*_coding:utf-8_*_

name = "Alex Li"

The above code declares a variable, the variable name is: name, the value of variable name is: "Alex Li"

Rules for variable definition:

① The variable name can only be any combination of letters, numbers or underscores
② The first character of the variable name cannot be a number
③ The following keywords cannot be declared as Variable name
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else ', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

Variable Assignment

name = "Alex Li"

name2 = name
print(name,name2)

name = "Jack"

print("What is the value of name2 now?")

The variable name should be as meaningful as possible so that people can know what the variable means at a glance.
If you want to represent a relational variable name, the general way of writing is:
gf_of_oldboy = "Chen da hua"
GFOfOldboy = "Chen da hua"
Not available in Python There is a concept of defining constants, but it is customary to use uppercase strings to represent constants. For example:
PIE = 3.1415926

Reserved fields cannot be used. Try not to use Chinese names and pinyin as variable names. This will Seems very low.


The difference and introduction of character encoding

In the Python2.X version, Chinese cannot be used directly. To use it, you must declare in advance:
# -*- coding:utf-8 -*-
name = "Hello, world"
print(name)

How to add comments to Python code:
1. Directly starting with # indicates a comment.
2. For multi-line comments, use three ['''] or ["""] before and after the code to be commented to put the content to be commented.

In addition, the contents included in ['''] or ["""] can be assigned to a variable as a whole for processing.
Example:

msg = '''
gf_of_oldboy = "wang da hua"
GFOfOldboy = "Chen rong feng"
'''

#print(gf_of_oldboy,GFOfOldboy)
print(msg)

Execution result:

gf_of_oldboy = "wang da hua"
GFOfOldboy = "Chen rong feng"

It should also be noted that The functions of single quotes and double quotes are similar to those in the shell. Single quotes represent strong references and double quotes represent weak references.


User interactive program
Formatted output specified content:
Method 1: ++ notation
name = input("Name:")
age = input("Age: ")
job = input("Job:")
salary = input("Salry:")

info = '''
---------- --------------- info of ''' + name +'''----------------------------- ---------------
Name:''' + name + '''
Age:''' + age + '''
Job:'' ' + job + '''
Salary:''' + salary + '''
--------------------- info of ''' + name + '''---------------------------------------------
'''
print(info)

Method 2: Placeholder representation

name = input("Name:")
#age = input("Age :")
age = int(input("Age:"))
print(type(age),type(str(age))) #The data type of age will be printed here and then converted into a string Then print out the data type, in order to verify whether the above conversion is effective
job = input("Job:")
salary = input("Salry:")

info2 = """
------------------------------ info of %s -------------- ----------------------------------
Name:%s
Age:%s #You can use % here d specifies that only integers can be input, not the default string, but the data type must be forced when input, otherwise an error will be reported
Age:%d
Job:%s
Salary:%s
. ----------------------------- info end %s ----------------- ----------------------------
""" %(name,name,age,job,salary,name)

print(info2)

Method 3: {} notation
name = input("Name:")
age = input("Age:")
job = input("Job:")
salary = input("Salry:")

info3 = """
----------------- ------------- info of {_name} -------------------------------- -------------
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
-- ---------------------------- info end {_name} ------------------ --------------------------
""" .format(_name=name,
_age=age,
_job=job,
_salary=salary)

print(info3)

Method 4: It is an extension of method 3, using numbers to represent specific variables

info4 = " ""
--------------------------------- info of {0} ---------- ----------------------------------
Name:{0}
Age:{1 }
Job:{2}
Salary:{3}
----------------------------- info end {0} ---------------------------------------------
""" .format(name,age,job,salary)

print(info4)

Note:
unless If you have no choice, try not to use it because it consumes too much memory. Other methods are much better.
Method 1 can be mixed with Method 2, Method 3, and Method 4, but Method 2, Method 3, and Method 4 cannot be mixed.

10. First introduction to modules

The power of Python is that it has a very rich and powerful standard library and third-party libraries, almost Any function you want to implement is supported by a corresponding Python library. In future courses, various commonly used libraries will be explained in depth. Now, let’s learn two simple ones symbolically.
sys module


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

import sys

print(sys.argv)


#Output
$ python test.py helo world
['test.py', 'helo', 'world'] #Execute The parameters passed during the script were obtained
 

os module


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

import os

os.system("df -h") #Calling system commands
Completely combine them


import os,sys

os.system(''.join(sys.argv[1:])) #Treat the parameters entered by the user as a command to os.system for execution


11. Selection expression if... else

!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: Bill Xie
import getpass
_username = "xiaoxie"
_password = "123456"
username = input( "username:")
password = input("password:")
#password = getpass.getpass("password:")
if _username == username and _password == password:
print ("Welcome user %s login."%(username))
else:
print("Invalid username or password!")

Notes:
1. Python code strictly requires grammatical abbreviation. If you don’t pay attention, you will get an error and indentation error
IndentationError: expected an indented block

The biggest difference between learning Python and other languages ​​is that Python code blocks do not use braces {} to control classes, functions and other logical judgments. The most distinctive feature of python is the use of indentation to write modules. The amount of indented whitespace is variable, but all code block statements must contain the same amount of indented whitespace, and this must be strictly enforced.

IndentationError: unexpected indent error is the python compiler telling you "Hi, brother, the format in your file is wrong. It may be that the tabs and spaces are not aligned." All python has very strict format requirements. .
If it is an IndentationError: unindent does not match any outer indentation level error, it means that the indentation methods you use are inconsistent. Some use tab key indentation, and some use space indentation. Just change it to the same one.
Therefore, the same number of leading spaces must be used in Python code blocks.
It is recommended that you use a single tab or two spaces or four spaces at each indentation level. Remember not to mix them.

2. Variable references are used in the print output command here. Let’s talk about it here. Two ways of variable reference.

① Similar to the method mentioned in the above comment, first use the %s placeholder, and then specify the variable to be used by the placeholder.
print("Welcome user %s login."%(username))
②Use curly braces {} to quote
print ("Welcome user {_username} login." .format(_username=username))
print("Welcome user {0} login." .format(username)) #Similar to the above, except that the number is replaced with a number Several variables to replace.

12. Loop body
Guessing game:

#!/usr/bin/env python
# - *- coding:utf-8 -*-
#Author: Bill Xie
age_of_oldboy = 29
guess_age = int(input("Guess oldboy's age:"))
if guess_age == age_of_oldboy:
print("You got it.")
elif guess_age > age_of_oldboy:
print("Think smaller...")
else:
print("Think bigger... ")

Instructions for inducing the loop:

while loop syntax:

 while condition:
  loop body
 esle: #Yes Without this
Loop body

for loop syntax:

for i in range (start number, end number, step size):
Loop body
else #can be omitted
Loop body

is not completed and needs to be updated. . . .

The above is the detailed content of Detailed introduction to the development origin and basic knowledge of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn