[Python] Python basic knowledge points


Novice tutorial: https://www.runoob.com/python3/python3-tutorial.html

1. Basic grammar

F8 step over:单步调试,把函数看作一行代码
F7 step into:单步执行代码,有函数则进入函数内部

The
first character of the identifier must be a letter in the alphabet or an underscore _.
The other parts of the identifier consist of letters, numbers, and underscores.
Identifiers are case sensitive.

1.1 Notes

There are single-line comments and multi-line comments in Python:

Single-line comments in Python start with #, for example:
#This is a comment
print("Hello, World!")
Multi-line comments use three single quotation marks "'or three double quotation marks """ to enclose the comment, for example :

1. Single quotation mark (''')
#!/usr/bin/python3
'''
This is a multi-line comment, use three single quotation marks
This is a multi-line comment, use three single quotation marks
This is a multi-line comment, use three A single quote
``'
print("Hello, World!")

2. Double quotation marks (""")
#!/usr/bin/python3
"""
This is a multi-line comment, use three double quotation marks
This is a multi-line comment, use three double quotation marks
This is a multi-line comment, use three Double quotes
"""
print("Hello, World!")

单行和多行注释均可用:Ctrl+/

1.2 Operator

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

Insert picture description here

1.3 Number

Python supports three different numeric types:

Integer (Int):- Usually referred to as an integer or an integer, it is a positive or negative integer without a decimal point. Python3 integer types have no size limit and can be used as Long types, so Python3 does not have Python2's Long types.

Floating point type (float):-Floating point type is composed of integer part and decimal part. Floating point type can also be expressed in scientific notation (2.5e2 = 2.5 x 102 = 250)

Complex number ((complex)):- A complex number consists of a real part and an imaginary part. It can be represented by a + bj, or complex(a,b). The real part a and imaginary part b of the complex number are both floating-point types.

Insert picture description here

1.4 String

Insert picture description here

1.5 Object-oriented

Fundamentals of object-oriented programming: "Compose a set of data structures and methods to process them into objects, group objects with the same behavior into classes, hide internal details through class encapsulation, and use inheritance. Realize the specialization and generalization of classes, and achieve dynamic assignment based on object types through polymorphism."

Insert picture description here

We said before that "a program is a collection of instructions". The statements we write in the program will become one or more instructions when executed and then executed by the CPU. Of course, in order to simplify the design of the program, we introduced the concept of function, put relatively independent and frequently reused code into the function, and only need to call the function when these functions are needed; if the function of a function is too complicated and bloated , We can further divide the function into sub-functions to reduce the complexity of the system.

But having said so much, I don't know if you have discovered that the so-called programming is that programmers control the computer to complete various tasks according to the way the computer works. However, the way the computer works is different from the normal human thinking mode. If you program, you have to abandon the normal way of thinking of humans to cater to the computer, and the fun of programming is much less. The rhetoric of "everyone should learn to program" I can only talk about it. Of course, these are not the most important ones. The most important thing is that when we need to develop a complex system, the complexity of the code will make development and maintenance work difficult, so in the late 1960s, the "software crisis" A series of concepts such as "software engineering" and so on began to appear in the industry.

Of course, everyone in the programmer circle knows that there is no "silver bullet" that solves the problems mentioned above in reality. What really gives software developers hope is the introduction of the Smalltalk programming language that was born in the 1970s. Object-oriented programming ideas (the prototype of object-oriented programming can be traced back to the earlier Simula language). According to this programming concept, the data in the program and the function of operating the data are a logical whole, which we call "objects", and the way we solve the problem is to create the required objects and send various kinds of objects to the objects. In the end, the collaborative work of multiple objects allows us to construct complex systems to solve real-world problems.

2. Basic variable types


There are six standard data types in Python3:

Number (number)
String (string)
List (list)
Tuple (tuple)
Set (collection)
Dictionary (dictionary)
Among the six standard data types of Python3:

Immutable data (3): Number (number), String (string), Tuple (tuple);
variable data (3): List (list), Dictionary (dictionary), Set (collection).

Insert picture description here

Number (Number) Type
There are four types of numbers in python: integers, booleans, floating-point numbers and complex numbers.

int (integer), such as 1, there is only one integer type int, which is represented as a long integer, and there is no Long in python2.

bool (Boolean), such as True.

float (floating point number), such as 1.23, 3E-2

complex (plural), such as 1 + 2j, 1.1 + 2.2j

String

The use of single quotes and double quotes in python is exactly the same.
Use triple quotation marks ("' or """) to specify a multi-line string.

The escape character ``
backslash can be used to escape, and the use of r can make the backslash not escape. . If r"this is a line with \n", \n will be displayed instead of a line break.
Concatenate strings literally, such as "this ""is" "string" will be automatically converted to this is string.
Strings can be concatenated with the + operator and repeated with the * operator.

There are two indexing methods for strings in Python, starting with 0 from left to right, and starting with -1 from right to left.
Strings in Python cannot be changed.
Python does not have a separate character type, a character is a string of length 1.
The grammatical format of string interception is as follows: variable [head subscript: tail subscript: step length]

3. Input and output

4. Conditional statement

5. Loop statement

6. Function

Insert picture description here
Python defines functions using the def keyword, and the general format is as follows:

def 函数名(参数列表):
    函数体

By default, parameter values ​​and parameter names are matched in the order defined in the function declaration.

Example
Let us use a function to output "Hello World!":

#!/usr/bin/python3
def hello() :
    print("Hello World!")

hello()

def sum_2_num(num1,num2):
	result = num1 + num2
	print("%d + %d = %d" % (num1,num2,result))
	return result
sum_result = sum_2_num(50,20)
print("计算结果:%d" % sum_result)

7. Module

#!/usr/bin/python3
# 文件名: using_sys.py
 
import sys
 
print('命令行参数如下:')
for i in sys.argv:
   print(i)
 
print('\n\nPython 路径为:', sys.path, '\n')
执行结果如下所示:

$ python using_sys.py 参数1 参数2
命令行参数如下:
using_sys.py
参数1
参数2

Python 路径为: [’/root’, ‘/usr/lib/python3.4’, ‘/usr/lib/python3.4/plat-x86_64-linux-gnu’, ‘/usr/lib/python3.4/lib-dynload’, ‘/usr/local/lib/python3.4/dist-packages’, ‘/usr/lib/python3/dist-packages’]

1. Import sys imports the sys.py module in the python standard library; this is the method of importing a certain module.
2. sys.argv is a list containing command line parameters.
3. sys.path contains a list of paths where the Python interpreter automatically finds the required modules.

Insert picture description here

from … import 语句
Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中,语法如下:

from modname import name1[, name2[, ... nameN]]

例如,要导入模块 fibo 的 fib 函数,使用如下语句:

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
这个声明不会把整个fibo模块导入到当前的命名空间中,它只会将fibo里的fib函数引入进来。

from … import * 语句
把一个模块的所有内容全都导入到当前的命名空间也是可行的,只需使用如下声明:

__name__属性
一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。

8. List

To create a list, simply enclose the different data items separated by commas in square brackets. As follows:

list1 = [‘Google’, ‘Runoob’, 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = [“a”, “b”, “c”, “d”]
list4 = [‘red’, ‘green’, ‘blue’, ‘yellow’, ‘white’, ‘black’]

Insert picture description here

9. Tuples

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

Use parentheses () for tuples and square brackets [] for lists.

Tuple creation is very simple, just add elements in parentheses and separate them with commas.

Insert picture description here

10. Dictionaries

Dictionary is another variable container model, and can store any type of object.

Each key value key=>value pair of the dictionary is separated by a colon:, and each pair is separated by a comma (,). The entire dictionary is enclosed in curly braces {}, the format is as follows:

d = {key1 : value1, key2 : value2, key3 : value3 }

Insert picture description here

11. Data structure

12. Class

Fundamentals of object-oriented programming: "Compose a set of data structures and methods to process them into objects, group objects with the same behavior into classes, hide internal details through class encapsulation, and use inheritance. Realize the specialization and generalization of classes, and achieve dynamic assignment based on object types through polymorphism."

Classes and objects: Simply put, a class is a blueprint and template of an object, and an object is an instance of a class. Although this explanation is a bit like using concepts to explain concepts, we can at least see from this sentence that classes are abstract concepts and objects are concrete things. In the world of object-oriented programming, everything is an object. Objects have attributes and behaviors. Each object is unique and must belong to a certain class (type). When we extract the static characteristics (attributes) and dynamic characteristics (behaviors) of a large number of objects that share common characteristics, we can define something called a "class".

Defining a class
In Python, you can use the class keyword to define a class, and then define methods in the class through the functions you have learned before, so that you can describe the dynamic characteristics of the object. The code is shown below.

Self represents an instance of a class,
and a method of a non-class class has only one special difference from ordinary functions-they must have an additional first parameter name, which is by convention self.
self represents the instance of the class, representing the address of the current object, and self.class points to the class.

class Student(object):

    # __init__是一个特殊方法用于在创建对象时进行初始化操作
    # 通过这个方法我们可以为学生对象绑定name和age两个属性
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def study(self, course_name):
        print('%s正在学习%s.' % (self.name, course_name))

    # PEP 8要求标识符的名字用全小写多个单词用下划线连接
    # 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
    def watch_movie(self):
        if self.age < 18:
            print('%s只能观看《熊出没》.' % self.name)
        else:
            print('%s正在观看岛国爱情大电影.' % self.name)

Explanation: The functions written in the class are usually called (object) methods. These methods are the messages that the object can receive.

Creating and using objects
After we define a class, we can create objects and send messages to them in the following ways.

def main():
    # 创建学生对象并指定姓名和年龄
    stu1 = Student('骆昊', 38)
    # 给对象发study消息
    stu1.study('Python程序设计')
    # 给对象发watch_av消息
    stu1.watch_movie()
    stu2 = Student('王大锤', 15)
    stu2.study('思想品德')
    stu2.watch_movie()


if __name__ == '__main__':
    main()

Object-oriented pillars
Object-oriented has three pillars: encapsulation, inheritance, and polymorphism. The latter two concepts are explained in detail in the next chapter. Here we first talk about what encapsulation is. My own understanding of encapsulation is to "hide all the implementation details that can be hidden, and only expose (provide) a simple programming interface to the outside world". The method we defined in the class actually encapsulates the data and the operation on the data. After we create the object, we only need to send a message (call the method) to the object to execute the code in the method, which means we You only need to know the name of the method and the parameters passed in (the external view of the method), not the implementation details of the method (the internal view of the method).

Exercise: Define a class to describe digital clocks.

from time import sleep

class Clock(object):
    """数字时钟"""

    def __init__(self, hour=0, minute=0, second=0):
        """初始化方法

        :param hour::param minute::param second:"""
        self._hour = hour
        self._minute = minute
        self._second = second

    def run(self):
        """走字"""
        self._second += 1
        if self._second == 60:
            self._second = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour = 0

    def show(self):
        """显示时间"""
        return '%02d:%02d:%02d' % \
               (self._hour, self._minute, self._second)

def main():
    clock = Clock(23, 59, 58)
    while True:
        print(clock.show())
        sleep(1)
        clock.run()

if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/m0_37882192/article/details/112685361