Python's Path to growth

Source: Internet
Author: User
Tags lua mathematical constants

Basic Article  

Chapter I. Python development, installation, use

1 , Python Introduction

2 , Python installation

3 , the first Python program

4 , Variables

5 , character encoding and binary

6 , the difference between character encodings

7 , If-else Process Judgment

8 , while Loops

Chapter I. Python development, installation, use Python the introduction

  Speaking of the Python language, you have to say that it was founded as Guido van Rossum (Guido van Rossum). During the Christmas of 1989, Guido van Rossum to spend time in Amsterdam, determined to develop a new script interpreter, as an inheritance of the ABC language.

Let's look at the latest Tiobe leaderboard.

  

It can be seen that Python has been in 2016, 2017 are in the fifth position, in the first five of the programming language only Python is growing trend, it can be seen that Python has been recognized by the industry.

The scenarios that Python can now apply are:

Web application Development

Python is often used for web development. For example, with the Mod_wsgi module, Apache can run web programs written in Python. Python defines the WSGI standard application interface to coordinate the communication between the HTTP server and the Python-based Web program. Some web frameworks, such as django,turbogears,web2py,zope, can make it easy for programmers to develop and manage complex web programs.

Operating System Management, server operations Automation scripts

In many operating systems, Python is the standard system component. Most Linux distributions, as well as NetBSD, OpenBSD, and Mac OS X, are integrated with Python and can be run directly under the terminal. Some installers for Linux distributions are written in the Python language, such as the Ubuntu ubiquity Installer, Red Hat Linux, and Fedora's Anaconda installer. Gentoo Linux uses Python to write its Portage package management system. The Python standard library contains multiple libraries that invoke operating system functionality. By Pywin32 This third-party package, Python has access to Windows COM services and other Windows APIs. Use the Ironpython,python program to directly invoke the. Net Framework. In general, the system management scripts written by Python are superior to normal shell scripts in terms of readability, performance, code reuse, and extensibility.

Scientific calculations

Numpy,scipy,matplotlib allows Python programmers to write scientific computing programs.

Desktop software

PyQt, Pyside, WxPython, and PYGTK are a powerful tool for Python to rapidly develop desktop applications.

Server Software (network software)

Python's support for various network protocols is perfect, so it is often used to write server software and web crawlers. The third-party library twisted supports asynchronous network programming and most standard network protocols (including clients and servers), and provides a variety of tools that are widely used to write high-performance server software.

Game

Many games use C + + to write high-performance modules such as graphical display, while using Python or Lua to write game logic, servers. Compared to Python,lua, the functionality is simpler and smaller, while Python supports more features and data types.

Concept implementation, early prototyping and iteration of the product

YouTube, Google, Yahoo!, and NASA all use Python in their own way.

There are other applications, such as data analysis and artificial intelligence .

Python Some of the interpreters CPython

When we downloaded and installed Python 3.5 from the official Python website, we immediately got an official version of the interpreter: CPython. This interpreter was developed in C language, so called CPython. Running Python at the command line is the start of the CPython interpreter.

CPython is the most widely used Python interpreter.

IPython

Ipython is an interactive interpreter based on CPython, meaning that Ipython is only enhanced interactively, but the functionality and CPython of executing Python code are exactly the same. Like many domestic browsers although the appearance of different, but the kernel is actually called ie.

CPython uses ">>>" as the prompt, while Ipython "in [ordinal]": as a prompt.

PyPy

PyPy is another Python interpreter whose goal is to perform speed. PyPy uses JIT technology to dynamically compile Python code (note that it is not interpreted), so it can significantly improve the execution speed of Python code.

Most python code can run under PyPy, but PyPy and CPython are somewhat different, which results in the same Python code being executed under both interpreters. 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 that compiles python code directly to Java bytecode execution.

IronPython

IronPython is similar to Jython, except that IronPython is a Python interpreter running on the Microsoft. NET platform that compiles python code directly into. NET bytecode.

Python some features of

Python is a programming language with a very large library, with very high development efficiency, portability, extensibility, and embedding, as an explanatory, dynamic type of strong definition type. Of course, it also has some shortcomings that the code is slow to execute, the code can not be encrypted, the thread can not take advantage of multi-CPU and so on.

In general, the programming language is a tool used to realize the engineer's thought. There's nothing good or bad about it. Only if you can take advantage of its characteristics, do not take the disadvantage of a program and a little contrast to another program.

Python the installation Window Platform Installation Python:

Here are the simple steps to install Python on the Window platform:

    • Open a Web browser to access https://www.python.org/downloads/windows/
    • In the download list, select the version you want to download, and here I choose the latest version of Python3.
    • To use setup python-xyz.msi, Windows systems must be supported with Microsoft Installer 2.0. Just save the installation file to your local computer, and then run it to see if your machine supports MSI. Windows XP and later versions already have MSI, and many older machines can also install MSI.
    • After downloading, double-click the download package, go to the Python Installation Wizard, the installation is very simple, you just need to use the default settings always click "Next" until the installation is complete.
    • Then it is the configuration environment variable "right-click Computer"-"Properties"-"Advanced system Settings"-"Advanced" and "Environment variable"-"Select Path under System Variables"-"SELECT Edit"-" Copy the Python installation directory to the last side of the line and remember to break the English delimiter when copying the installation directory. "
Unix & Linux Platform Installation Python

In general, now the Linux default installation Python2, if not installed, follow the steps below to install:

    • Open a Web browser to access http://www.python.org/download/
    • Select the source compression package for unix/linux.
    • Download and unzip the zip package.
    • If you need to customize some options to modify modules/setup
    • Execute the./configure script
    • Make
    • Make install

After doing this, Python is installed in the/usr/local/bin directory, and the Python library is installed in/USR/LOCAL/LIB/PYTHONXX,XX for the version number of the python you are using.

MAC Platform Installation Python

Now the MAC has the environment variable by default as long as the official website to download the appropriate version can be used

Write the first Python program

I am using the programming software is pycharm in the inside to create the corresponding file on OK, about how to use pycharm oneself can surf the internet to search related articles.

The result of the execution is:

If the top of the script in the Linux system is actually added #! /usr/bin/env python This means that when the program is executed, it will fetch the first python specified in the path of your machine to execute your script. This is written to prevent some python from being installed in the default location. In the execution of the program, a few of the corresponding execution permissions to the file: chmod a+x *.py can be executed in the current directory:./*.py. Or the direct Python *.py is also valid if you do not give permission.

variablesRules for variable definitions:
    • Variable names can only be any combination of letters, numbers, or underscores
    • The first character of a variable name cannot be a number
    • The following keywords cannot be declared as variable names
      [' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' fr ' Om ', ' global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' Try ', ' when ', ' with ' , ' yield ']
the habit of naming variables

Want to be a good programmer first we must have good programming habits, when your code more write more time will find you define the variables will be more and more, in order to increase the readability of the code and convenient debugging, the variable name must follow certain naming habits, The name of your variable is best to give a glimpse of what this variable is for, for example, getusername that the variable should be to get the user's name.

Check_current_conn_count representative is to check the number of connections now, so that other people can see your code when the role of these variables, and if you put the variable name full Var1,var2,var3.....varn, So other people in reading the code is not worth the variable is what to do, to others to read the code or debugging to bring difficulties so that others will look at the side scold you, at the same time you do not know what they mean.

The definition of variable name in the premise can express its role is the most concise the better, can use a word clearly expressed as far as possible do not use two. Variables are usually named when there are so many ways of writing, you think which is the most concise, you choose which kind of it.

Checkcurrentconncount

Check_current_conn_count

Checkcurrentconncount

Bad naming:

Checkcurrentconncount

Var1 var2 Var3 Varn

Checkcurrentconncount

Assignment of variables:

The assignment of a variable in Python is equivalent to a reference mechanism, such as the above example: the system first stores the corresponding "Yangpan" string in memory, and then points the variable name to the address in memory where "Yangpan" is stored:

In Python we create a variable name and assign the variable name to the next variable, name2. In fact, make the variable name2 point to the address in memory and the variable name to the same location as the memory address. When the variable name changes the assignment, the variable name points to an address in memory that changes, and the variable name2 to the address in memory does not change. Specific in-memory changes such as:

Attention:

1, assigning variables such as name = "China Yang" Note this must be enclosed in English double quotation marks, double quotation marks inside the letter or number is not continuous outside must have double quotation marks

2, name2 = name This does not double quotation marks to assign the variable name to Name2

3, Name3 = "name" This means assigning the string "name" to Name3

4, Name4 = True This is a Boolean value and is generally used as a logical judgment.

Constant

As for the variables, there is also a concept is constant, so-called constants are immutable variables, such as the usual mathematical constants π is a constant. In Python, constants are typically represented in all uppercase variable names:

PI =3.14159265359

But in fact pi is still a variable, Python does not have any mechanism to ensure that PI will not be changed, so, using all uppercase variable names to represent constants is only a customary usage, if you must change the value of the variable pi, no one can stop you.

Character encoding

Because a computer can only handle numbers, if you are working with text, you must convert the text to a number before processing it. The oldest computer was designed with 8 bits (bit) as a byte (byte), so a single word energy-saving representation of the largest integer is 255 (binary 11111111 = decimal 255), if you want to represent a larger integer, you must use more bytes. For example, two bytes can represent the largest integer is 65535, 4 bytes can represent the largest integer is 4294967295.

Since the computer was invented by the Americans, only 127 letters were encoded into the computer, that is, letters, numbers, and symbols, which are referred to as ASCII encoding, such as the code for capital A is 65, and the lower case z is encoded as 122.

But to deal with the Chinese is clearly a byte is not enough, at least two bytes, but also cannot and ASCII encoding conflict, so, China has developed a GB2312 code, used to put Chinese into.

What you can imagine is that there are hundreds of languages all over the world, Japan has made Japanese into Shift_JIS, South Korea has made Korean into EUC-KR, and countries have standards, inevitably conflict, the result is that in multi-language mixed text, the display will be garbled.

As a result, Unicode emerges. Unicode unifies all languages into a set of encodings, so there is no more garbled problem.

The Unicode standard is also evolving, but it is most commonly used to represent a character in two bytes (4 bytes If a very remote character is used). Unicode is supported directly by modern operating systems and most programming languages.

Now, the difference between ASCII encoding and Unicode encoding is smoothed: ASCII encoding is 1 bytes, and Unicode encoding is usually 2 bytes.

The letter A with ASCII encoding is decimal 65, binary 01000001;

The character 0 is in ASCII encoding is decimal 48, binary 00110000, note that the character ' 0 ' and the integer 0 are different;

The ASCII encoding range has been exceeded in Chinese characters, with Unicode encoding being decimal 20013, binary 01001110 00101101.

You can guess that if you encode ASCII-encoded A in Unicode, you only need to make 0 on the front, so the Unicode encoding for A is 00000000 01000001.

The new problem arises again: If Unicode encoding is unified, the garbled problem disappears. However, if you write text that is basically all in English, using Unicode encoding requires more storage space than ASCII encoding, which is not cost-effective in storage and transmission.

Therefore, in the spirit of saving, there has been the conversion of Unicode encoding to "Variable length encoding" UTF-8 encoding. The UTF-8 encoding encodes a Unicode character into 1-6 bytes according to a different number size, the commonly used English letter is encoded in 1 bytes, the kanji is usually 3 bytes, and only the very uncommon characters are encoded into 4-6 bytes. If the text you want to transfer contains a large number of English characters, you can save space with UTF-8 encoding:

Character

Ascii

Unicode

UTF-8

A

01000001

00000000 01000001

01000001

In

X

01001110 00101101

11100100 10111000 10101101

It can also be found from the table above that the UTF-8 encoding has an added benefit that ASCII encoding can actually be seen as part of the UTF-8 encoding, so a large number of legacy software that only supports ASCII encoding can continue to work under UTF-8 encoding.

Figuring out the relationship between ASCII, Unicode, and UTF-8, we can summarize how the current computer system works with character encoding:

In computer memory, Unicode encoding is used uniformly, and is converted to UTF-8 encoding when it needs to be saved to the hard disk or when it needs to be transferred.

When editing with Notepad, the UTF-8 characters read from the file are converted to Unicode characters into memory, and when the edits are complete, the conversion of Unicode to UTF-8 is saved to the file:

When you browse the Web, the server converts dynamically generated Unicode content to UTF-8 and then to the browser:

So you see many pages of the source will have similar <meta charset= "UTF-8"/> Information, that the page is exactly the UTF-8 code.

The above-mentioned character coding is to see Alex's teacher. Personal feeling written in a concise and clear, able to understand very well

If-else Process Judgment

The IF statement is the first to say one of the built-in functions in Python input () to interact with user implementations by reading the console input

If statement:

The syntax is as follows:

If expression:

Do this

Elif sxpression:

Do this

....

Else

Do this

If the value of expression in expressions is true (any value that is nonzero is true), or the expression is formed, the program executes the indented content (be sure to indent correctly). If this is not the case, the following elif statement is also seen to see that the value of expression is true (no zero value is true), or the expression is set. The content after the indentation is executed. If you do not succeed, you will always have the following elif statement until the end of the entire process when the Else statement is executed, or to end the process judgment if the previous if statement or Elif statement succeeds. A simple guessing age game to achieve this process judgment. This game can only be played once

Using the If-else statement, we can nest judgment statements in a judgment statement, such as the following mini-game.

While loop

While looping the language hair structure

While expression:

While_suite

When expression in the while is not 0 or flash, the statement while_suite is executed continuously until the value of expression is 0 or the flash ends the loop.

Continue, break statement

Again to the while loop, say the difference between jumping out of the loop statement break and ending the continue of the loop statement. The statement of the entire while loop will end when the break statement is executed in the re-loop statement. Then, when executing to the Continue statement, if the value of the while expression is not 0 or flash only ends the current loop, starts the next loop until the break statement is executed or the value of expression in while is 0 or flash, The entire while loop does not return to the end. Below we ask 1 to 100 all even sums of sum:

By the above 2 columns can be happy to distinguish the break statement to the end of the entire loop, and continue when the end of the current loop to start the next cycle.

For loop

The For loop can traverse any sequence of items now in this we simply say for loop application.

For <variable> in <sequence>:

<statements>

Else

<statements>

Before we say it, let's start with the range function, the range function generates a list of lists.

The I in range (i) represents the generation of a list from 0 to i-1, or it can be expressed with xrange (i) About

The result of the xrange output is the same as the range, but it doesn't generate a list immediately. He returned a generator.

So the performance of Xrange cycle is better than range , especially when the return is very large!

Try to use xrange , unless you want to return a list with range.

Now talk about the for loop.

At the top of the sake we can see that every time we create a list object in range (5) go to a value and then output, and then take a value in the output, until the end of the fetch. This is the FOR loop.

I don't say much about the for loop, this is a new person.

I first write a blog, the individual also feel good writing, but I personally mainly deepen their knowledge. I will continue to write, I hope that in the future when writing a blog in deepening their understanding, can make some progress to some small white bring help

Python's Path to growth

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.