Chapter 1: Getting to Know Python

Chapter 1: Getting to Know Python

Resource directory: Code (1)
Article resource download: (1-15 chapters)
Link: https://pan.baidu.com/s/1Mh1knjT4Wwt__7A9eqHmng?pwd=t2j3
Extraction code: t2j3
or go to the column "python tutorial" to view

Introduction to Python

History of Python

  1. Christmas 1989: Guido von Rossum starts writing a compiler for the Python language.
  2. February 1991: The first Python compiler (also an interpreter) was born, which was implemented in C language (later), and can call library functions in C language. In the earliest version, Python has provided support for building blocks such as "classes", "functions", and "exception handling", as well as core data types such as lists and dictionaries, and supports building applications based on modules .
  3. January 1994: Python 1.0 is officially released.
  4. October 16, 2000: Python 2.0 was released, adding full garbage collection and providing support for Unicode . At the same time, the entire development process of Python has become more transparent, the influence of the community on the development progress has gradually expanded, and the ecological circle has gradually formed.
  5. December 3, 2008: Python 3.0 was released, it is not fully compatible with the previous Python code, but because there are still many companies using Python 2.x version in projects and operation and maintenance, so many new Python 3.x The feature was later ported to Python 2.6/2.7 as well.

The version of Python 3.7.x I am currently using was released in 2018. The version number of Python is divided into three sections, shaped like ABC. Among them, A represents the major version number. Generally, A is added when the overall rewrite or incompatible changes occur; B represents a function update, and B is added when a new function appears; C represents a small change (for example: repairing a certain Bug), add C as long as there is a modification. If you are interested in the history of Python, you can read an online article called "A Brief History of Python".

Advantages and disadvantages of Python

Python has many advantages, which can be summarized as follows.

  1. Simple and clear, with a low learning curve, it is easier to learn than many programming languages.
  2. Open source, with a strong community and ecosystem, especially in the fields of data analysis and machine learning.
  3. An interpreted language is inherently platform-portable, and the code can work on different operating systems.
  4. Both major programming paradigms (object-oriented programming and functional programming) are supported.
  5. The code is highly standardized and readable, and is suitable for people with code cleanliness and obsessive-compulsive disorder.

The shortcomings of Python mainly focus on the following points.

  1. The execution efficiency is slightly lower, and the parts that require high execution efficiency can be written in other languages ​​(such as: C, C++).
  2. The code cannot be encrypted, but now many companies do not sell software but sell services, this problem will be weakened.
  3. There are too many frameworks to choose during development (for example, there are more than 100 web frameworks), and where there are choices, there will be mistakes.

Applications of Python

At present, Python is widely used in the fields of web application back-end development, cloud infrastructure construction, DevOps, network data collection (crawler), automated testing, data analysis, machine learning, etc.

Install the Python interpreter

If you want to start the journey of Python programming, you must first install the Python interpreter environment on your computer. The following will take the installation of the official Python interpreter as an example to explain how to install the Python environment on different operating systems. The official Python interpreter is implemented in C language and is the most widely used Python interpreter, usually called CPython. In addition, the Python interpreter also has Jython implemented in the Java language, IronPython implemented in the C# language, and versions such as PyPy, Brython, and Pyston. Interested readers can learn by themselves.

Windows environment

You can download the Python Windows installer (exe file) from the Python official website. It should be noted that if you install Python 3.x in the Windows 7 environment, you need to install the Service Pack 1 patch package first (you can automatically install the system through some tool software patch function to install), during the installation process, it is recommended to check "Add Python 3.x to PATH" (add Python 3.x to the PATH environment variable) and select custom installation, it is best to set "Optional Features" in the "Optional Features" interface Check all items such as pip", "tcl/tk", and "Python test suite". It is strongly recommended to choose a custom installation path and ensure that there is no Chinese in the path. After the installation is complete, you will see a "Setup was successful" prompt. If there is a problem that the Python interpreter cannot work due to the lack of some dynamic link library files when running the Python program later, you can solve it according to the following method.

If the system displays that the api-ms-win-crt*.dll file is missing, you can refer to the method explained in the article "Api-ms-win-crt*.dll missing cause analysis and solution" or directly download Visual C++ from Microsoft's official website Redistributable for Visual Studio 2015 files to repair; if some dynamic link library files are missing after updating Windows DirectX, you can download a DirectX repair tool to repair.

Linux environment

The Linux environment comes with Python 2.x version, but if you want to update to 3.x version, you can download the source code of Python from the official website of Python and install it by building and installing the source code. The specific steps are as follows (Take CentOS as an example).

  1. Install dependencies (since without them the source code artifact installation may fail due to missing underlying dependencies).
yum -y install wget gcc zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
  1. Download the Python source code and extract it to the specified directory.
wget https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tar.xz
xz -d Python-3.7.6.tar.xz
tar -xvf Python-3.7.6.tar
  1. Switch to the Python source code directory and execute the following commands to configure and install.
cd Python-3.7.6
./configure --prefix=/usr/local/python37 --enable-optimizations
make && make install
  1. Modify the file named .bash_profile in the user's home directory, configure the PATH environment variable and make it take effect.
cd ~
vim .bash_profile
# ... 此处省略上面的代码 ...

export PATH=$PATH:/usr/local/python37/bin

# ... 此处省略下面的代码 ...
  1. Activate environment variables.
source .bash_profile

macOS environment

macOS also comes with Python 2.x version, and you can install Python 3.x version through the installation file (pkg file) provided by Python's official website . After the default installation is complete, you can pythonstart the 2.x version of the Python interpreter by executing the command on the terminal, and you need to execute python3the command to start the 3.x version of the Python interpreter.

run python program

Confirm the version of Python

You can type the following commands at the Windows command line prompt.

python --version

Type the command below in a terminal on your Linux or macOS system.

python3 --version

Of course, you can also enter pythonor python3enter the interactive environment first, and then execute the following code to check the version of Python.

import sys

print(sys.version_info)
print(sys.version)

Write Python source code

You can use text editing tools ( advanced text editing tools such as Sublime and Visual Studio Code are recommended) to write Python source code and save the file with py as the suffix. The code content is as follows.

print('hello, world!')

run the program

Switch to the directory where the source code is located and execute the following command to see if "hello, world!" is output on the screen.

python hello.py

or

python3 hello.py

comments in the code

Annotation is an important part of programming language, which is used to explain the function of the code in the source code to enhance the readability and maintainability of the program. Of course, the code segments in the source code that do not need to participate in the operation can also be removed through comments , which is often used when debugging programs. Comments will be removed when entering the preprocessor or compiling with the source code, and will not remain in the object code and will not affect the execution result of the program.

  1. Single-line comments - sections starting with # and spaces
  2. Multi-line comments - start with three quotes, end with three quotes
"""
第一个Python程序 - hello, world!
向伟大的Dennis M. Ritchie先生致敬

Version: 0.1
Author: 骆昊
"""
print('hello, world!')
# print("你好, 世界!")

Python development tools

IDLE - In-house integrated development tool

IDLE is an integrated development tool that comes with the Python environment, as shown in the figure below. But because IDLE's user experience is not so good, it is rarely used in actual development.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-bI1X3Cos-1679059205850)(./res/python-idle.png)]

IPython - A Better Interactive Programming Tool

IPython is an interactive interpreter based on Python. Compared with the native Python interactive environment, IPython provides more powerful editing and interactive functions. You can install IPython through the Python package management tool pip, and the specific operation is as follows.

pip install ipython

or

pip3 install ipython

After the installation is successful, you can start IPython through the following ipython command, as shown in the figure below.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-bD5zfB4f-1679059205851)(./res/python-ipython.png)]

Sublime Text - Advanced Text Editor

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-mbR6AKkw-1679059205852)(./res/python-sublime.png)]

  • First, you can download and install Sublime Text 3 or Sublime Text 2 through the official website .

  • Install package management tools.

    1. Use the shortcut key Ctrl+` or select Show Console in the View menu to open the console, and enter the following code.
    • Sublime 3
    import  urllib.request,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib.request.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())
    
    • Sublime 2
    import  urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp)ifnotos.path.exists(ipp)elseNone;urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read());print('Please restart Sublime Text to finish installation')
    
    1. Enter https://sublime.wbond.net/Package%20Control.sublime-package in the browser to download the installation package of the package management tool, and find the directory named "Installed Packages" under the Sublime installation directory, and put the file just downloaded Add it to this file, and then restart Sublime Text to get it done.
  • Install the plugin. Open the command panel through the Package Control of the Preference menu or the shortcut key Ctrl+Shift+P, enter Install Package in the panel to find the tool for installing the plug-in, and then find the required plug-in. We recommend that you install the following plugins:

    • SublimeCodeIntel - Code completion tool plugin.
    • Emmet - Front-end development code template plugin.
    • Git - Version control tool plugin.
    • Python PEP8 Autoformat - PEP8 specification auto-formatting plugin.
    • ConvertToUTF8 - Convert native encoding to UTF-8.

Explanation : In fact, Visual Studio Code may be a better choice. It does not cost money and provides more complete and powerful functions. Interested readers can do their own research.

PyCharm - Python development artifact

The installation, configuration and use of PyCharm are introduced in "Playing with PyCharm" , and interested readers can choose to read it.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-DsnIbhNH-1679059205852)(./res/python-pycharm.png)]

practise

  1. Enter the following code in the Python interactive environment and view the results, please try to translate what you see into Chinese.

    import this
    

    Explanation : Enter the above code, and you can see "Zen of Python" written by Tim Peter in the interactive environment of Python . The principles described in it are not only applicable to Python, but also applicable to other programming languages.

  2. Learn to use turtle to draw graphics on the screen.

    Explanation : turtle is a very interesting built-in module of Python, especially suitable for friends who have first experience in computer programming. It was originally part of the Logo language, which is a programming language invented by Wally Feurzig and Seymour Papert in 1966.

    import turtle
    
    turtle.pensize(4)
    turtle.pencolor('red')
    
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    
    turtle.mainloop()
    

    Tips : The codes provided in this chapter also include the codes for drawing the national flag and drawing Peppa Pig. Interested readers should do their own research.

Guess you like

Origin blog.csdn.net/xyx2023/article/details/129628546