Python - advanced dynamic programming language - getting started Basics

Posted by elecktricity on Fri, 04 Mar 2022 11:20:38 +0100

Python overview

TIOBE index in January 2021

January Headline: Python is TIOBE's Programming Language of 2020!

Python has won the TIOBE programming language of the year award! This is for the fourth time in the history, which is a record! The title is awarded to the programming language that has gained most popularity in one year. Python made a positive jump of 2.01% in 2020. Programming language C++ is a very close runner up with an increase of 1.99%. Other winners are C (+1.66%), Groovy (+1.23%) and R (+1.10%).
It has been stated before: Python is popping up everywhere. It started as a competitor of Perl to write scripts for system administrators a long time ago. Nowadays it is the favorite language in fields such as data science and machine learning, but it is also used for web development and back-end programming and growing into the mobile application domain and even in (larger) embedded systems. The main reasons for this massive adoption are the ease of learning the language and its high productivity. These two qualities are key in a world that is craving for more developers in all kinds of fields. Python already tested the second position some months ago and it will for sure swap places with Java permanently soon. Will Python also beat C? Well, C has still one trump card to play: its performance, and this will remain the case for some time to come. So I guess it will certainly take some years for Python to become the new number 1 in the TIOBE index.

The above is an excerpt from the article published by TIOBE in January 2021. At the beginning of the article, python won the annual TIOBE programming language award! It is the fourth time in history to set a record! The title was awarded the most popular programming language of the year. Python achieved a positive growth of 2.01% in 2020.

Through the growth trend chart in the figure below, it is not difficult to see that Python is growing year by year and is expected to exchange positions with Java.

Python origin

Python was invented by Dutch Guido van Rossum during Christmas 1989. The first public release was issued in 1991.

In 1982, Guido received a master's degree in mathematics and computer from the University of Amsterdam. However, although he is a mathematician, he enjoys the fun of computer more. In his words, despite his qualifications in mathematics and computer, he always tends to do computer related work and is keen to do anything related to programming. At that time, he contacted and used languages such as Pascal, C, Fortran and so on. The basic design principle of these languages is to make the machine run faster.

In the 1980s, the configuration of personal computers was extremely low compared with today. For example, in the early Macintosh, there was only 8MHz CPU frequency and 128KB RAM, and a large array could fill the memory. The core of all compilers is to optimize so that the program can run. In order to improve efficiency, language also forces programmers to think like computers so that they can write programs that are more in line with the taste of machines. It is precisely because of this that Guido is distressed. He thought it was too time-consuming to write a program like this, so he thought of a shell. Bourne Shell has long existed as an interpreter of UNIX system. UNIX administrators often use the shell to write some simple scripts for system maintenance, such as regular backup, file system management and so on. Shell can be like glue to connect many functions under UNIX. Many hundreds of lines of programs in C language can be completed in only a few lines under the shell. However, the essence of the shell is to call commands. It is not a real language. The shell can not fully mobilize the functions of the computer.

Therefore, Guido began to think about whether to design a language that has the advantages of both C and shell. It can not only call the functional interface of the computer, but also write programs easily.

Later, he joined CWI (centrum wiskunde & Informatica, Institute of mathematics and computer) in the Netherlands and participated in the development of ABC language. ABC language aims at teaching. Unlike most languages at that time, the goal of ABC language was to "make users feel better". ABC language hopes to make the language easy to read, easy to use, easy to remember and easy to learn, so as to stimulate people's interest in learning programming. For example, the following is the source code of this ABC program:

HOW TO RETURN words document:

  PUT {} IN collection

  FOR line IN document:

   FOR word IN split line:

​     IF word NOT.IN collection:

​      INSERT word IN collection

  RETURN collection

HOW TO is used to define a function. It should be easy FOR a python programmer to understand this program. ABC language uses colons and indents to represent program blocks (C language uses pairs of braces to represent program blocks). There is no semicolon at the end of the line. There are also no parentheses in the FOR and IF structures. IF you change HOW TO to to def, change PUT line to collection = [], and INSERT line to collection Append (word), which is almost a standard Python function. The above function reads like a natural text.

Although it has good readability and ease of use, ABC language did not become popular in the end. At that time, ABC language compiler needed a highly configured computer to run. The users of these computers are usually proficient in computers. They think more about the efficiency of the program than the difficulty of learning. In addition to the difficulties in hardware, there are also some fatal problems in the design of ABC language: poor scalability, no direct IO, excessive innovation and communication difficulties, which makes it unacceptable to most programmers (because the excessive innovation in grammar increases the learning difficulty of programmers) and communication.

Apart from these shortcomings, it is not difficult to see that ABC is the rudiment of the language expected by Guido.

During Christmas in 1989, in Amsterdam, Guido decided to develop a new script interpreter as an inheritance of ABC language in order to kill the boredom of Christmas. Named python, it is from his favorite TV series Monty Python's flying circle.

In 1991, the first Python compiler was born. It is implemented in C language and can call C library (. so file). Since its birth, python has had core data types including class es, function s, exception handling, list s and dictionaries, as well as module based expansion systems.

In order to avoid repeating the mistakes of ABC, Guido pays attention to the scalability of python, and also follows most of the syntax habits in C, which makes Python popular with Guido colleagues. They quickly gave feedback on the use of Python and participated in the improvement of Python.

In the early 1990s, personal computers began to enter ordinary families. Intel released 486 processor, and windows released a series of Windows systems starting with windows 3.0, which greatly improved the performance of the computer. Due to the improvement of computer performance, the world of software began to change. The hardware is enough to meet the needs of many personal computers. Hardware manufacturers are even eager for the emergence of high demand software to drive the upgrading of hardware. C + + and Java are popular one after another. C + + and Java provide object-oriented programming paradigm and rich object library. At the expense of certain performance, C + + and Java greatly improve the output of programs. The ease of use of language has been raised to a new level.

We remember that an important reason for ABC failure is the performance limitation of hardware. In this regard, python was born at a lucky time. Python is much luckier than ABC.

Another quietly changing is the Internet. The 1990s was still the era of personal computers. windows and Intel took advantage of PC s to make the world prosperous. Although the information revolution dominated by the Internet has not yet arrived, many programmers and senior computer users have been using the Internet frequently for communication (including email and newsgroup). The Internet has greatly reduced the cost of information exchange. A new software development model has become popular: open source. Programmers use their spare time to develop software and open source code. In 1991, Linus worked in comp os. The Linux kernel source code was released on the MINIX newsgroup, attracting a large number of hacker s. Linux and GNU cooperate with each other and eventually form a dynamic open source platform.

As the Internet is widely known with the popularity of personal computers, many programmers and senior computer users frequently use the Internet for communication, which makes Python free of hardware constraints and communication difficulties. In addition, Python is easy to use, which makes Python spread to a certain extent.

Hardware performance is not a bottleneck, and Python is easy to use, so many people began to turn to python. Guido maintains a mail list to communicate with Python users via email. Because Python users come from many fields and have different backgrounds, they also have different needs for Python. Python is quite open and easy to expand, so when users are not satisfied with the existing functions, it is easy to expand or transform python. These users then send the changes to Guido, who decides whether to add the new features to Python or the standard library. This makes the advantages of different fields focus on python.

Later python 2 0, from the development mode of mail list to the fully open source development mode, the expansion speed and propagation speed of python database are further improved.

Today, the framework of Python has been established. Python language takes object as the core, organizes code (Everything is object), supports multiple programming paradigms, adopts dynamic typing, and automatically performs garbage collection. Python supports interpret ation and can call C library for expansion. Python has a powerful standard library (battery included). Since the system of the standard library has been stable, Python's ecosystem has begun to expand to third-party packages.

Python has entered 3 The age of X. Since Python 3.0 is backward incompatible, from 2.0 To x.3 The transition of X is not easy. On the other hand, the performance of Python is still worth improving. The computing performance of Python is lower than that of C + + and Java. Python is still a developing language.

Python design positioning

Python's design philosophy is "elegant", "clear" and "simple".

Therefore, the concept of "there are always many ways to do the same thing" in Perl is usually unbearable among Python developers. The philosophy of Python developers is ["one way, preferably only one way to do one thing"]. When designing a python language, if faced with multiple choices, python developers generally reject fancy syntax and choose explicit syntax with no or little ambiguity. Due to this difference in design concepts, python source code is generally considered to have better readability than Perl and can support large-scale software development. These guidelines are called Python maxims. Run import this within the Python interpreter to get a complete list.

Python developers try to avoid immature or unimportant optimizations. Some faster patches for unimportant parts are usually not incorporated into python. So many people think Python is slow. However, according to the 28 law, most programs do not require high speed. In some cases with high requirements for running speed, python designers tend to use JIT technology or rewrite this part of the program in C/C + + language. The available JIT technology is PyPy.

Python is a completely object-oriented language. Functions, modules, numbers, and strings are objects. It fully supports inheritance, overloading, derivation and multi inheritance, which is beneficial to enhance the reusability of source code.

Python supports overloaded operators and dynamic types. Compared with LISP, the traditional functional programming language, python only provides limited support for functional design. Two standard libraries (functools, itertools) provide the proven functional programming tools in Haskell and Standard ML.

Although Python may be roughly classified as a "script language", in fact, it is widely used by Google for some large-scale software development plans, such as Zope, Mnet and BitTorrent. Supporters of Python prefer to call it a high-level dynamic programming language because "scripting language" generally refers to languages that only do simple programming tasks, such as shellsript, VBScript and other programming languages that can only deal with simple tasks, which can not be compared with Python.

Python itself is designed to be extensible. Not all features and functions are integrated into the language core. Python provides rich API s and tools so that programmers can easily use C and C + + to write expansion modules. The python compiler itself can also be integrated into other programs that need scripting language. Therefore, many people also use Python as a "glue language". Use Python to integrate and encapsulate programs written in other languages

In many projects within Google, for example, Google Engine uses C + + to write parts with high performance requirements, and then uses Python or Java/Go to call the corresponding modules.

Martelli Alex, author of the python technical manual, said: "It's hard to say. However, in 2004, python has been used internally by Google. Google recruited many Python experts, but they have decided to use Python before. Their purpose is Python where we can, C++ where we must, C + + where we must, use C + + when controlling hardware, and use Python when developing quickly."

Zen of Python

Run import this in the Python interpreter to get the python Maxim written by Tim Peters. The original text is as follows:

The Zen of Python, by Tim Peters

 

Beautiful is better than ugly.

Beauty is better than ugliness

Explicit is better than implicit.

Clarity is better than obscurity

Simple is better than complex.

Simplicity is better than complexity

Complex is better than complicated.

Complexity is better than complexity

Flat is better than nested.

Flat is better than nested

Sparse is better than dense.

Sparse is better than dense

Readability counts.

Readability counts 

Special cases aren't special enough to break the rules.

These rules should not be violated under special circumstances

Although practicality beats purity.

But reality is often not so perfect

Errors should never pass silently.

Exceptions should not be handled silently

Unless explicitly silenced.

Unless you want to

In the face of ambiguity, refuse the temptation to guess.

In case of ambiguity, don't guess

There should be one-- and preferably only one --obvious way to do it.

There must be one and usually the only best solution

Although that way may not be obvious at first unless you're Dutch.

Although this scheme is not obvious, because you are not the Dutchman

[Here means Python Father of Guido]

Now is better than never.

It's better to do it now than not

Although never is often better than *right* now.

Doing nothing is better than doing it blindly[In extreme programming YAGNI principle]

If the implementation is hard to explain, it's a bad idea.

If an implementation is difficult to understand, it is not a good solution

If the implementation is easy to explain, it may be a good idea.

If an implementation is easy to understand, it is likely to be a good solution

Namespaces are one honking great idea -- let's do more of those!

Namespaces are very useful and we should make more use of them

Python features

  1. Easy to learn:

Python has relatively few keywords, simple structure, and a well-defined syntax, which is easier to learn.

  1. Easy to read:

Python code is more clearly defined.

  1. Easy maintenance:

Python's success lies in its open source source code, which is very easy to maintain.

  1. Rich community support:

One of the biggest advantages of Python is that it has rich libraries, cross platform, and is well compatible with UNIX, Windows and Mac.

  1. Interoperable:

Support interactive programming, that is, you can input and execute code from the terminal and obtain results, which is convenient for testing and debugging code fragments.

  1. Portable:

Based on its open source nature, Python has been ported (that is, made to work) to many platforms.

  1. Scalable:

If you need a fast running key code, or you want to write some algorithms that do not want to be open, you can use C or C++ to complete that part of the program and then call it from your Python program.

  1. Embeddable:

Python can be embedded into C/C + + programs, so that users of your program can get the ability of "scripting".

Python shortcomings

Because Python is an interpretive language, the code written is the execution code, which is both its advantages and disadvantages.

Slow down

When a python program is executed, the Python interpreter reads the source code and executes it at the same time, which is inefficient.

Python is basically not considered when developing high-performance programs. However, in ordinary application level programs that do not pursue extreme efficiency, the disadvantage of slow Python is not obvious, while Python is simple, efficient and has obvious advantages in development ability, so it is widely used.

Ø unable to encrypt

The process of Python program publishing is the process of publishing the source code. The code cannot achieve the effect of confidentiality, but it is precisely because of this feature that Python is naturally open source from the language level, which is also one of the reasons for the rapid development of Python community.

Python is widely used

Ø website development: Django, pyramid, bolt, tornado, flask, web2py

Ø GUI development: Tkinter, pygobject, pyqt, pyside, Kivy, wxpathon

Ø science and numerical computation: Science, pandas, IPython

Ø software development: Buildbot, Trac, Roundup

Ø system management: Ansible, Salt, OpenStack

Python development environment construction

Python download and installation

Official download address: https://www.python.org/downloads/ , you can download all available Python distributions and corresponding user manuals from this link. After installation, configure the installation directory and its script directory into PATH, so that Python can be used on the command line:

Python environment detection

You can view the current Python version through the python -V instruction, which indicates that the current development environment is available, or you can enter Python directly through the command line to enter the python interactive interface, which indicates that the environment is successfully installed, for example:

Python Basics

Python interactive programming

There is no need to create script files, but to write code through the interactive mode of Python interpreter. For example, after entering the python interactive interface through the command line, python will execute the input Python code one by one, for example, enter print("Hello World!"), Execute this line of code immediately after entering, as shown in the following figure:

Python scripted programming

Just like C/Java and other programming languages, the source program needs to be written. The difference is that it does not need to be compiled into the target program and then executed. Instead, the source program is interpreted and executed through the python interpreter until the execution is completed.

Hello World

Create a new hello Py file to The file with py as suffix is generally called Python source program or script file. Write a line of code in this file as follows:

print("****Hello World****!")

Explain and execute

After writing the script file, you can use Python hello The PY command calls the Python interpreter to interpret and execute the script file.

Of course, python commands can be used directly on the Linux platform. Because in most current Linux distributions, Python interpreter is basically built in, as shown below:

[root@centos ~]# python Hello.py

Hello World!

In addition, we can also execute the script by indicating the specific location of the python interpreter in the first line of the script, as shown below:

#!/bin/python

print(**"****Hello World****!"**)

After writing the script file, set the permission of the file to executable through the chmod command, and then it can be used in the current directory/ Hello.py to execute the script, as follows:

[root@centos ~]# ./Hello.py

Hello World!

Whether the specific location of the parser is specified in the script or not, you can use Python hello The PY command calls the interpreter to interpret and execute the script, which is also the recommended practice.

Python2.x and python 3 Difference between X

Python version 3.0 is often called Python 3000, or Py3k for short. This is a major upgrade from earlier versions of Python.

In order not to bring too much burden, python 3.0 did not consider downward compatibility in its design. In order to take care of the existing programs, python 2.6, as a transitional version, basically uses Python 2.6 X syntax and library, considering the migration to Python 3.0, allowing the use of some Python 3.0 syntax and functions.

Most third-party libraries are working hard with Python 3 X compatible. Even if you cannot use Python 3.0 immediately, it is recommended to write a program compatible with Python 3.0 and then use Python 2.6 or Python 2.7 to run it.

Python 3.0 changes mainly in the following nine aspects (including but not limited to):

print function

In 2 In X, using the print function allows no parentheses, as shown below:

\>>> print "hello"

hello

In 3 In X, the print function must be used with parentheses, as shown below:

\>>> print "hello"

 File "<stdin>", line 1

  print "hello"

​     ^

SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?

Unicode

In 2 In the X version, the default code of the script file is ASCII format. When the coding format is not modified, Chinese characters cannot be printed correctly, so an error will be reported when reading Chinese, as shown below:

[root@centos ~]# python Hello.py

 File "Hello.py", line 1

SyntaxError: Non-ASCII character '\xe4' in file Hello.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

To solve this problem, we need to declare the file code at the beginning of the script file, that is, just add # - * - coding: UTF-8 - * - or # coding=utf-8 at the beginning of the file. As follows:

# coding=utf-8
print("Hello!!")

In 3 X, the default encoding of its script file is UTF-8 format. Therefore, Chinese can be parsed normally without specifying UTF-8 code.

Division operation

Division in Python has two operators, / and / /. We take 10 ÷ 3 as an example to compare the operation results of the two versions, as shown below:

In Python 2.7.5:

\>>> 10/3

3

\>>> 10//3

3

In Python 3.8.7:

\>>> 10/3

3.3333333333333335

\>>> 10//3

3

It is not difficult to see that in 3 The function of / / in X is the same as that in C language or Java language. It directly discards the decimal places for simple integer operation, while the function of / will retain the decimal places.

abnormal

In 3 In X, the syntax for catching exceptions is changed from except exc, var to except exc as var. We take dividing by zero as an example to compare the operation results of the two versions, as shown below:

In Python 2.7.5:

try:
    print(10 / 0)
except ZeroDivisionError, e:
    print("Error dividing by zero:" + e.__doc__)

In Python 3.8.7:

try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("Error dividing by zero:" + e.__doc__)

xrange

In 2 The xrange() function used to create the iteration object in X is in 3 X is replaced by the range() function, and the comparison is shown below:

In Python 2.7.5:

for x in xrange(3):
    print(x)

In Python 3.8.7:

for x in range(3):
    print(x)

Octal literal representation

We take decimal 32 as an example to compare two different versions of octal literal representation, as shown below:

In Python 2.7.5:

\>>> 040

32

In Python 3.8.7:

\>>> 0o40

32

In 3 In the x version, the number 0 and the letter o need to be prefixed to indicate that the literal quantity is octal. This format is also true in hexadecimal. Hexadecimal needs to prefix the number 0 and the letter x to indicate the literal quantity.

not equal operator

In 2 In X, there are not two ways to write= And < >, while in 3 The writing method of < > is abandoned in X.

In Python 2.7.5:

\>>> 2 != 3

True

\>>> 2 <> 3

True

In Python 3.8.7:

\>>> 2 != 3

True

\>>> 2 <> 3

 File "<stdin>", line 1

  2 <> 3

​    ^

SyntaxError: invalid syntax

The repr expression is discarded

In 2 The back quotation mark in X is equivalent to 3 The role of the repr function of X is in 3 This notation is removed from X and only the repr function is allowed. Examples of comparison are as follows:

In Python 2.7.5:

\>>> repr({"name":"timor", "age":3})

"{'age': 3, 'name': 'timor'}"

\>>> `{"name":"timor", "age":3}`

"{'age': 3, 'name': 'timor'}"

In Python 3.8.7:

\>>> repr({"name":"timor", "age":3})

"{'name': 'timor', 'age': 3}"

\>>> `{"name":"timor", "age":3}`

 File "<stdin>", line 1

  `{"name":"timor", "age":3}`

  ^

SyntaxError: invalid syntax

data type

3.x discards the long type

In 3 X discards the long type and retains only one integer - int. the comparison example is as follows:

In Python 2.7.5:

\>>> type(9999999999999999999)

<type 'long'>

In Python 3.8.7:

\>>> type(9999999999999999999)

<class 'int'>

3.x new bytes type

In 3 In X, a new type of bytes is added, corresponding to 2 The comparison example of the octet string of version x is as follows:

In Python 2.7.5:

\>>> type(b'hello')

<type 'str'>

In Python 3.8.7:

\>>> type(b'hello')

<class 'bytes'>

3.x modified the iterator of the dictionary

In 3 In X, the return iterators of the keys, items and values methods of the dictionary have been banned The iterkeys, iteritems, and itervalues methods of the dictionary in X. Examples of comparison are as follows:

In Python 2.7.5:

d = {"name": "timor", "age": 3}

for x in d.iterkeys():
    print(x)

for x in d.itervalues():
    print(x)

for x in d.iteritems():
    print(x)

In Python 3.8.7:

d = {"name": "timor", "age": 3}

for x in d.keys():
    print(x)

for x in d.values():
    print(x)

for x in d.items():
    print(x)

Programming specification

Python code line

  1. Usually a line is a statement without semicolons.

  2. If you write multiple lines on the same line, you need to break sentences with semicolons to place ambiguities.

  3. Python does not use braces as the identification of the scope, but tabs to identify the scope.

Python comments

Python uses # as a symbol for a single line comment. It is also commonly used as a feature declaration of a script, such as declaring the code of the current document, or declaring the full path of the current document interpreter.

Python identifier

In Python, all identifiers can include English, numbers and underscores, but cannot start with a number. And case sensitive. In addition, the underline in Python has special meaning. When using it, you should pay attention to the following points:

  1. Identifiers starting with a single underscore represent inaccessible members, similar to private in Java

  2. Use double underscores at the beginning and end to represent special member specific identifiers. For example, init() represents the constructor of the class

Python reserved word

Reserved words cannot be used as constants or variables, or any other identifier names. You can find a list of all keywords in Python documents, as shown below:

-----
Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield

Of course, in different versions, reserved words are not necessarily limited to the reserved words shown in the above table. For details, you can view them through the module of importing keywords, as shown below:

\>>> from keyword import kwlist

\>>> print(kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

\>>> len(kwlist)

35

Python variables and constants

Python does not declare the keyword of reference. Writing the identifier directly is to declare a reference variable, and the declared reference variable has no type difference. That is, the same reference variable can point to different types of data successively. When necessary, you can use the type function to obtain the type of the reference variable, as shown below:

x = 100
print(type(x))
x = 0o40
print(type(x))
x = 0x20
print(type(x))
x = 3.14
print(type(x))
x = 'A'
print(type(x))
x = "Hello"
print(type(x))

The output results are as follows:

<class 'int'>

<class 'int'>

<class 'int'>

<class 'float'>

<class 'str'>

<class 'str'>

In python, it is agreed that if the reference identifier is written in all uppercase, it is called a constant. It should be noted that its essence is still a variable, and the python interpreter allows its value to be re assigned.

Operators and Expressions

Arithmetic operator

--
+Sum
-Difference seeking
*quadrature
/Seeking quotient
//Integer division (rounding down)
%Take mold
**Power

Example:

\>>> a = 3; b = 2

\>>> a+b

5

\>>> a-b

1

\>>> a*b

6

\>>> a/b

1.5

\>>> a//b

1

\>>> a%b

1

\>>> a**b

9

Relational operator

--
==be equal to
!=Not equal to
>greater than
<less than
>=Not less than
<=Not greater than

Example:

\>>> a = 3; b = 2

\>>> a==b

False

\>>> a!=b

True

\>>> a>b

True

\>>> a<b

False

\>>> a>=b

True

\>>> a<=b

False

Assignment Operators

--
+=Summation assignment
-=Difference assignment
*=Quadrature assignment
/=Quotient assignment
//=Integer division assignment (rounding down)
%=Modular assignment
**=Power assignment

Example:

\>>> a = 7; b = 2

\>>> a+=b; a,b

(9, 2)

\>>> a-=b; a,b

(7, 2)

\>>> a*=b; a,b

(14, 2)

\>>> a/=b; a,b

(7.0, 2)

\>>> a//=b; a,b

(3.0, 2)

\>>> a**=b; a,b

(9.0, 2)

\>>> a%=b; a,b

(1.0, 2)

Bitwise Operators

--
&And
|or
^XOR
~Reverse
<<Shift left
>>Shift right

Example:

\>>> 1&0

0

\>>> 1&1

1

\>>> 1|1

1

\>>> 1|0

1

\>>> 1^1

0

\>>> 1^0

1

\>>> 0^0

0

\>>> ~1

-2

\>>> ~0

-1

\>>> 4 << 1

8

\>>> 4 >> 1

2

Tips: shift left and right operators are usually very efficient when dividing 2 and its multiples or multiplying 2 and its multiples.

Logical operator

--
andAnd
oror
notwrong

The standard expression will be used to identify the true value of the program:

If x is false or omitted, this returns False; otherwise it returns True

Therefore, for numbers, non-zero is true, and for other reference types, non empty is true

Example:

\>>> bool(1 and True)

True

\>>> bool(0 and True)

False

\>>> bool(0.0 and True)

False

\>>> bool(0.1 and True)

True

\>>> bool("" and True)

False

\>>> bool("Fasle" and True)

True

\>>> bool({} and True)

False

\>>> bool({"name": "timor"} and True)

True

\>>> bool([] and True)

False

\>>> bool([1] and True)

True

member operator

--
inJudge whether members exist
not inJudge whether the member does not exist

Example:

\>>> 1 in [1,3,5]

True

\>>> 2 in [1,3,5]

False

\>>> 3 not in [1,3,5]

False

\>>> "name" in {"name":"timor"}

True

\>>> "age" in {"name":"timor"}

False

\>>> "name" not in {"name":"timor"}

False

Identity operator

--
isCompare whether the storage unit (memory address) of two objects is the same
is notCompare whether the storage unit (memory address) of two objects is not the same

Example:

\>>> a=3; b=2

\>>> a is b

False

\>>> a is not b

True

\>>> id(a) == id(b)

False

\>>> id(a) != id(b)

True

\>>> a=2; b=2

\>>> a is b

True

\>>> a is not b

False

\>>> id(a) == id(b)

True

\>>> id(a) != id(b)

False

Program control structure

In order to maintain the integrity of the program structure, whether it is a branch structure, a loop structure, or a class or function, if there are no statements in the structure, you need to use pass to indicate that the current structure belongs to an empty structure.

Branching structure

if True:
   pass
if True:
    print("It is true!")
else:
    print("It is false!")

Unlike the if structure in Java, Python's if structure can assign values to reference variables, similar to the ternary operator in Java, for example:

a = 3.14 if 100 > 100 else 2.68
 

Cyclic structure

Python supports break and continue key to control loops, and its function is the same as that in Java.

while loop

x = 100

while x > 0:
    print(x)
    x -= 1

for loop

The for loop is used to traverse any sequence structure, such as string, list, tuple, etc. As follows:

tuples = ("timor", 1, 3.14)

for i in tuples:
    print(i)

tuples = ["timor", 1, 3.14]

for i in tuples:
    print(i)

The range(start, stop, step) function can generate a sequence of [start, stop) intervals in steps of step, which can be used to cycle a specific number of times in the for loop. It is as follows:

for i in range(1, 30, 4):
    print(i)

Built in object

--
packageUsed to get the package name of the current module
docGets the document description of the reference object
nameIt is used to uniquely identify the module imported into the system.

Built in function

Mathematical correlation

Function nameFunction descriptionUse example
absReturn absolute valueabs(-2)
divmodTake two (non complex) numbers as parameters. When integer division is used, the tuple of quotient and modulus is returneddivmod(10, 3)
maxReturns the maximum value of the specified elementmax(2,3,4)
minReturns the minimum value of the specified elementmin(2,3,4)
powReturns the power result of the parameterpow(2,3)
roundroundinground(2.675)
sumSumsum([2,3,4])

Type related

Function nameFunction descriptionUse example
ordReturns an integer value representing the corresponding Unicode character codeord('a')
chrReturns the Unicode character code corresponding to the integer valuechr(97)
strReturns the representation of a stringstr(1)
intReturns an integer in decimal representationint("2")
octReturns an integer in octal representationoct(32)
hexReturns an integer in hexadecimal representationhex(12)
floatConvert parameter to float typefloat(2)
binConverts an integer to a binary string prefixed with "0b".bin(10)
boolConverts a parameter to a bool value, one of True and Falsebool(10)
bytesConvert parameter to bytes typebytes(20)
listCreate a list type objectlist()
tupleCreate an object of tuple typetuple()
dictCreate an object of dictionary typedict({})
setCreate an object of collection typeset()

Common functions

Function nameFunction descriptionUse example
printPrintoutprint("Hello")
inputReceive data input from the consoleinput()
typeReturns the type of the reference variabletype(2)
lenReturns the total number of elements in the containerlen("ok")
rangeGenerate a sequence within the specified rangerange(2,20,1)
enumerateReturns the enumeration object of the sequence, including its elements and indexenumerate([33 , 99])
sortedSort the sequencesorted([2,3,4])
reversedReverse the sequencereversed([2,3,4])
zipGenerate an iterator to aggregate elements from each iterablezip([2,3], [5,6])
allReturns true if all elements in the sequence are trueall([0, 1])
anyReturns true if any element in the sequence is trueany([0, 1])

Other functions

Function nameFunction descriptionUse example
exitExit programexit()
quitsign outquit()
isinstanceDetermine whether the object is an instance of a classisinstance(1, float)
issubclassDetermine whether a word class is a subclass of a classissubclass(C, A)
openOpen a fileopen("/a.txt")
idReturns the identity of the object. In CPython, it refers to the address of the object in memory.id(1)
reprReturns a string containing a printable representation of an objectrepr({"name": "Timo"})
asciiReturns a string of printable representations of an object. Non ASCII strings will be escaped using \ x, \u or \ Uascii({"name": "Timo"})
evalAnalyze and evaluate Python expressionseval("3+1")
callableWhether the called object can be judgedcallable(int)
delattrDelete the property of the object, which is declared in the constructordelattr(c, "gender")
getattrGets the value of the property of the objectgetattr(c, "name")
hasattrJudge whether the attribute of the object existshasattr(c, "name")
dirReturns the list of names in the current local scope without parameters.dir()
helpView the document introduction of the specified objecthelp()

Python data structure

Duck type

A programming style that does not look at the type of object to determine whether it has the correct interface; Instead, a method or property is simply called or used ("if it looks like a duck and quacks like a duck, it must be a duck"), and well-designed code is replaced by allowing polymorphism by emphasizing interfaces rather than specific types.

Number type

Python supports three different number types: int (signed integer), float (floating point), and complex (complex).

Python supports complex numbers. Complex numbers are composed of real and imaginary parts, which can be represented by a + bj or complex(a,b). The real part a and imaginary part B of complex numbers are floating-point.

\>>> 

\>>> # positive integer

\>>> print (149600000000)

149600000000

\>>> # negtive integer

\>>> print (-149600000000)

-149600000000

\>>> # hexadecimal

\>>> print (0x22D4DAD800)

149600000000

\>>> # Floating point number

\>>> print (3.141592653589793)

3.141592653589793

\>>> # complex

\>>> print (-1j)

-1j

String type

Python can use single quotation marks ('), double quotation marks ("), three quotation marks (') or" "" ") to represent strings. The beginning and end of quotation marks must be of the same type.

The string represented in pairs of three quotation marks can be composed of multiple lines. Newline and escape symbols will be ignored, which is generally called text block. For example:

\>>> 

\>>> print ("Hello World!")

Hello World!

\>>> print ('Hello world!')

Hello world!

\>>> print ('''

<html>

  <head>

​    <title>Python</title>

  </head>

  <body>

​    <h1>Hello Python String Block! </h1>

  </body>

</html>

''')


<html>

  <head>

​    <title>Python</title>

  </head>

  <body>

​    <h1>Hello Python String Block! </h1>

  </body>

</html>

 

Document string

A string literal that appears as the first expression within a class, function, or module. It will be ignored during code execution, but will be recognized by the interpreter and put into the doc attribute of the class, function or module. Because it can be used for code introspection, it is the standard location for objects to store documents. For example:

\>>> def fun ():

​    "I am the document string of the function"

​    pass

 

\>>> print (fun.__doc__)

I am the document string of the function

Original string

In the string represented by paired single quotation marks or double quotation marks, \ n \ t, etc. are escaped as special symbols. If escape is not required, add the letter "R" or "R" before the first quotation mark of the string to form the original string. All its strings are used directly according to the literal meaning, and there is no escape of special or non printable characters. For example:

\>>> 

\>>> print ('a\tb')

a   b

\>>> print (r'a\tb')

a\tb

String formatting

Python strings support the use of% to format strings, as shown below:

\>>> "My name is %s." % "Timor"

'My name is Timor.'

\>>> "My name is %s, I`m %d years old." % ("Timor", 12)

'My name is Timor, I`m 12 years old.'

Python string formatting symbol list:

Symboldescribe
%cFormatted characters and their ASCII codes
%sformat string
%dFormat integer
%uUnsigned integer
%oFormat unsigned octal number
%xFormat unsigned hexadecimal number
%XFormat unsigned hexadecimal number (uppercase)
%fFormat floating-point numbers to specify the precision after the decimal point
%eFormatting floating point numbers with scientific counting
%EThe function is the same as%e, format floating-point numbers with scientific counting method
%g%Abbreviations for f and% e
%G%Abbreviations for F and% E
%pFormat the address of a variable with a hexadecimal number

When formatting decimal places, if you need to keep the decimal places, you can use them in the following ways, as shown below:

"PI is %.3f" % 3.1415926

When formatting a string, if you need to keep%, you can use two%%, as shown below:

"32 %% 3 = %d" % 2

The function format of string can also be used to format string. This syntax is similar to% formatting in most cases, except that {} and: are added to replace%. For example, '% 03.2f' can be rewritten as' {: 03.2f} '.

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'

Access parameters by name:

>>> 'a is: {a}, b is: {b}'.format(a='37', b='-115')
'a is: 37, b is: -115'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

Use comma as thousands separator:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

Expressed as a percentage:

>>> 'Correct answers: {:.2%}'.format(19/22)
'Correct answers: 86.36%'

Common string operations

section

Python string can obtain the characters at the corresponding position in a way similar to array subscript, as shown below:

"hello"[1]

There are two order of values obtained by subscript:

l the index from left to right starts from 0 by default, and the maximum range is 1 less than the string length

l the index from right to left starts with - 1 by default, and the maximum range is the beginning of the string

Processing some elements of a list in Python is called slicing. The format of [header subscript: tail subscript] can be used to intercept the corresponding string. The subscript starts from 0 and can be positive or negative. The subscript can be empty, which means to get the head or tail. The corresponding results are as follows:

x = "Hello"

 

x[1:3]  => el

x[-4:-2] => el

x[-2:-4] => 

-------------------

x[:3]  => Hel

x[:-2]  => Hel

-------------------

x[1:]  => ello

x[-4:]  => ello

-------------------

x    => Hello

x[:]   => Hello

Python string interception can receive the third parameter. The parameter is a positive integer, which is used to represent the interception step size, for example:

operation

The plus sign (+) is a string concatenation operator and the asterisk (*) is a repeat operation. Examples are as follows

\>>> "ab" + "cd"

'abcd'

\>>> "ab" * 2

'abab'

In and not in determine whether it is included. Examples are as follows:

\>>> "a" in "abcd"

True

\>>> "e" in "abcd"

False

List type

statement

vs = ["timor", 'male', 20, 42.6]
print("vs`length is %d." % vs.__len__())
 

ergodic

for v in vs:
    print(v)

# Get the element and its subscript through enumerate
for (i, v) in enumerate(vs):
    print("i = %d, v = %s" % (i, v))
 

increase

vs.append(30)
print(vs)
vs.insert(1, "insert to 1")
print(vs)
vs.extend([55, 66])
print(vs)
# List connection
vs += [77, 88]
print(vs)
# Duplicate list
vs *= 2
print(vs)
 

modify

vs[1] = "update by 1"
print(vs)
 

Value

print(vs[1])
 

delete

# Delete the specified element, and an exception will appear when it cannot be found
vs.remove(3333333)
print(vs)
# Delete last in list
p = vs.pop()
print(p)
print(vs)

Other operations

# Count the number of times an element appears in the list
c = vs.count(66)
print(c) 

# Find the first matching index position of a value from the list
c = vs.index(66)
print(c) 

# Reverse list
vs.reverse()
print(vs) 

# List sorting is in ascending order by default. If descending order is required, it can be reversed to descending order after ascending.
vs = [43, 6, 10, 3, 20]
# Ascending order
vs.sort()
print(vs)
vs = [43, 6, 10, 3, 20]
# Descending order
vs.sort(reverse=True)
print(vs)

Tuple type

Python tuples are similar to lists, except that the elements of tuples cannot be modified.

statement

vs = ("timor", 'male', 20, 42.6)
print("vs`length is %d." % vs.__len__())
print("vs`length is %d." % len(vs))

ergodic

for v in vs:
    print(v)

# Get the element and its subscript through enumerate
for (i, v) in enumerate(vs):
    print("i = %d, v = %s" % (i, v))

increase

The elements of tuples cannot be modified. Tuples can be changed by concatenation and repetition

# Tuple connection
vs += (77, 88)
print(vs)
# Tuple repetition
vs *= 2
print(vs)

modify

Elements of tuples are not modifiable

Value

print(vs[1])

delete

Element of tuple cannot be deleted

Dictionary type

A dictionary is another variable container model and can store objects of any type. Each key value pair of the dictionary is separated by colon. Each key value pair is separated by comma. The whole dictionary is included in curly brackets {}. The keys of the dictionary cannot be repeated and are out of order. The structure of the dictionary is the same as that of the JSON object.

statement

vs = {"name": "timor", "gender": 'male', "age": 20, "weight": 42.6}
print("vs`length is %d." % vs.__len__())
print("vs`length is %d." % len(vs))

ergodic

for v in vs:
    print(v)

# Get the element and its subscript through enumerate
for (i, v) in enumerate(vs):
    print("i = %s, v = %s" % (i, v))

# Traverse the value of the element through the values function
for v in vs.values():
    print("value = %s" % v)

# Traverse the keys of the element through the keys function
for k in vs.keys():
    print("key = %s, value = %s" % (k, str(vs[k])))

# Traverse the elements through the items function, and each element is a tuple
for kv in vs.items():
    print("key = %s, value = %s" % (kv[0], kv[1]))

increase

vs["address"] = "Wuhan"
print(vs)
# Update the key / value pair of the parameter dictionary in the current dictionary
vs.update({"position": "Software Development Engineer", "name": "Mary"})
print(vs)

modify

vs["name"] = "jack"

Value

print(vs["name"])
print(vs.get("name"))

delete

# Delete according to key
p = vs.pop("position")
print(p)
print(vs)
# Delete last
p = vs.popitem()
print(p)
print(vs)
# Empty the entire dictionary
vs.clear()
print(vs)

Collection type

set object is a collection of different objects, which is unordered and non repeatable. Common uses include member testing, removing duplicates from sequences, and calculating mathematical operations such as intersection, union, difference, and symmetric difference.

statement

vs = {"timor", 'male', 20, 42.6}
print("vs`length is %d." % vs.__len__())
print("vs`length is %d." % len(vs))

ergodic

for v in vs:
    print(v)

# Get the element and its subscript through enumerate
for (i, v) in enumerate(vs):
    print("i = %s, v = %s" % (i, v))

increase

vs.add(3.14)
vs.add(3.14)
print(vs)
vs.update({33, 44})
print(vs)

Modification and value

set does not support modifying values through subscripts, nor does it support taking values through subscripts

delete

vs.discard(33)
print(vs)
vs.remove(44)
print(vs)
p = vs.pop()
print(p)
print(vs)
vs.clear()
print(vs)

Sequence unpacking

Strings, lists, tuples, dictionaries and collections can be traversed (unpacked) in at least two ways:

for v in vs:
    print(v)

for (i, v) in enumerate(vs):
    print("i = %d, v = %s" % (i, v))

example

Instance: authentication

Prompt the user to enter the user name and password. Login is successful only when the user name is root and the password is root, otherwise prompt to re-enter.

# --coding:utf-8--
# Instance: authentication
username = input("Please enter account number:")
while username != "root":
    username = input("Invalid account, please re-enter the account:")

password = input("Please input a password:")
while password != "root":
    password = input("The account and password do not match. Please re-enter the password:")

print("account number%s Successfully logged in" % username)

Example: temperature conversion

Celsius scale: the unit is ° C

Taking water as the temperature measuring material under 1 standard atmospheric pressure, the fixed melting point is 0 ° C and the boiling point is 100 ° C.

Fahrenheit scale: the unit is ° F

Taking mercury as the temperature measuring material under 1 standard atmospheric pressure, the fixed melting point is 32 degrees and the boiling point is 212 degrees, and the temperature is described in equal parts.

According to the definitions of Fahrenheit and Celsius, there is the following conversion formula:

C = (F - 32) ÷ 1.8

F = C × 1.8 + 32

Script example:

# coding=utf-8

# Fahrenheit temperature conversion formula

f = input("Please enter Fahrenheit:")
f = float(f)
c = (f - 32) / 1.8

print(f, "°F = ", c, "°C")

# Celsius temperature conversion formula

c = input("Please enter Celsius:")
c = float(c)
f = c * 1.8 + 32

print(c, "°C = ", f, "°F")

Example: Calculator

After entering two numbers and operators through the console, calculate and output the results. The execution process is as follows:

python Calculator.py

Please enter the first integer: 4

Please enter the second integer: a

Invalid input, please re-enter the second integer: 6

Please enter an operator(+, -, *, /, //): plus

Invalid input, please re-enter operator(+, -, *, /, //): +

4 + 6 = 10

Script example:

# --coding:utf-8--
# Example: Calculator

a = input("Please enter the first integer:")
while not isinstance(a, int):
    try:
        a = int(a)
    except ValueError as e:
        a = input("Invalid input, please re-enter the first integer:")

b = input("Please enter the second integer:")
while not isinstance(b, int):
    try:
        b = int(b)
    except ValueError as e:
        b = input("Invalid input, please re-enter the second integer:")

c = input("Please enter an operator(+, -, *, /, //): ")
while c not in ['+', '-', '*', '/', '//']:
    c = input("Invalid input, please re-enter operator(+, -, *, /, //): ")

if '+' == c:
    d = a + b
elif '-' == c:
    d = a - b
elif '*' == c:
    d = a * b
elif '/' == c:
    d = a / b
else:
    d = a // b

print("%d %s %d = %d" % (a, c, b, d))

Example: business card output

After inputting the name, telephone number and address through the console, print the text progress bar for about ten seconds, and finally format and output the input information. The execution process is as follows:

python Card.py

Please enter your name: wonderful code

Please enter your mobile number: 182****9070

Please enter your address: Wuhan, Hubei

 

 

Business card generation in progress............

 

 

〓〓〓〓〓〓〓〓〓〓〓

Name: wonderful code

Tel: 182****9070
 
Address: Wuhan, Hubei

〓〓〓〓〓〓〓〓〓〓〓

Script example:

# --coding:utf-8--

import time

name = input("Please enter your name:")
phone = input("Please enter your mobile number:")
address = input("Please enter your address:")

print("\n Business card generation in progress..", end="")
for x in range(0, 10):
    print(".", end="",flush=True)
    time.sleep(1)


print("""

〓〓〓〓〓〓〓〓〓〓〓
full name: %s
 Telephone: %s
 Address: %s
〓〓〓〓〓〓〓〓〓〓〓
""" % (name, phone, address))
 

Example: stone scissors cloth

Input r, s and p through the console to represent stone, scissors and cloth respectively. Then the computer (NPC) will randomly produce stone scissors and paper. After logical comparison, it will output whether the Player wins or not. The process is as follows:

python Rock-Paper-Scissors.py

Please enter( r: Stone, s: Scissors, p: Cloth) p

cloth(player)  VS stone(npc)

You won

An example of a script program is as follows:

# --coding:utf-8--
# Example: stone scissors cloth
import random

KEYS = ['r', 's', 'p']
ROLES = ['stone', 'scissors', 'cloth']
MAX = len(ROLES) - 1

player = input("Please enter( r: Stone, s: Scissors, p: Cloth)")
while player not in KEYS:
    player = input("Input error, please enter( r: Stone, s: Scissors, p: Cloth)")

iPlayer = KEYS.index(player)
player = ROLES[iPlayer]

iNpc = random.randint(0, 2)
npc = ROLES[iNpc]

print("%s(player) VS %s(npc)" % (player, npc))

if iNpc == iPlayer:
    print("it ends in a draw")
elif min(iPlayer, iNpc) == 0 and max(iPlayer, iNpc) == MAX:
    print("you%s Yes" % ("win" if iPlayer > iNpc else "Defeat"))
elif iPlayer < iNpc:
    # By default, the smaller the subscript, the larger the subscript
    print("You won")
else:
    print("You failed")
 

Topics: Python Programming