#第3篇Sharing: Python Basic Grammar-Sharpening the Knife and Chopping Wood

#pythonbasic grammar
No matter what language we learn, we have to learn the basic grammar and some basic definitions of the language at first. The following figure basically covers all the basic knowledge of python learning. Let me talk about the previous one in detail. Good forgive me:
Insert picture description here

1. First introduce the data types: python data types, including numbers, strings, lists, tuples, dictionaries, collections:
a. Number types include: integer: int(1/2/3), floating point: float (3.14), plural: complex(a+bi);

b. String str: str (number), three single quotes:''' xxx''', double quotes: "xxx", single quotes:'xxx';

c. List (variable, ordered) list: can store strings: name = ["Zhang San", "Li Si", "Wang Wu"], can store numbers: num=[1,2,3];
Syntax: read element name[0/1/2], list merge: name+num ->print(name+num), element add append: name.append(num[1]), element delete: del name[1 ] , list delete: del name slice (cut out part of the data to form a new list): name(start:end:step)

d. Tuple (immutable, ordered) tuple: name = ("Zhang San", "Li Si", "Wang Wu"), num=(1,2,3); (Immutable means that it cannot be deleted individually A certain element corresponds to a list)
Syntax: read element: name[0], meta combination: name+num, change tuple: name = num, delete tuple: del name, slice (cut out part of the data to form a New tuple): num(start:end:step);

e. Dictionary (variable, unordered) dict: name ={'f':'123','y':'124','h':'125'}; (disordered, relying on key-value pair recognition)
Syntax: read value: name['f']->'123', add element: name[key] = value,
delete element: del name['h'];

f. Set (variable, unordered, unique): name = {f, y, h},name1 = {f, y};
Syntax: add element: name.add('a'), delete element: remove. name(f),
delete set: del name, operation of intersection, union and difference: name&name1
name|name1 name-name1
Note: view data type: type(xxx)

2. The operators of python are basically the same as those of other languages . It will be easier to understand if you have a programming foundation:
a. Arithmetic operators: +, -, *, /,% (remainder), // (rounding), ** (Power)
b. Logical operators: and, or, not (Result: True, False)
c. Assignment operators: a= b
d. Comparison operators: >, <, ==, >=, <= ,!=
e. Bit operators: & (bit AND), | (bit OR), ^ (bit exclusive OR), ~ (bit inversion)
<< (left shift operator), >> (right shift operator) )

Note: Priority issues: semicolons separate levelsInsert picture description here

3. Python basic sentences:
a. Input function: a= int(input("Please enter a value")) b= int(input("Please enter a value"))->For variable numerical variables, you can use the input function , Such as age;
b. Output function: print(a,b,"I love little turtle")->For data we are not sure about, we can use this function to print, and observe whether the output is ideal;
Note:
#1. Comment code: ( I don’t want to delete the code yet, or add a description to the code):
// The content of the comment, ``'comment content''', Ctrl + / (Quick comment/uncomment)
#2.Python is very strict for indentation, That is, the codes of the same level must be aligned, otherwise an error will be reported;

4. The python conditional control statement if, when we need to choose, we can use the if statement to control, the following is the basic usage:

if 条件1print(1)
 elif 条件2:
  print(2)
 elif 条件3:
  print(3)
 else:
  print('当以上条件都不满足时,我能显示出来!')
 解释:
  当条件1成立时,输出1,后面的语句不会执行
  当条件1不成立,条件2成立时,输出2,条件2后面的语句不会执行
  当条件1和条件2都不满足,条件3成立时,输出3,条件3后面语句不会执行
  当条件123都不满足时,执行else语句,输出'当以上条件都不满足时,我能显示出来!'

Examples show:

#美观注释方法
'''
作者:天甜费
昵称:一飞冲天咻咻
人生格言:爱代码,爱人生
import xxxx
from   xxxx  import xxx
'''
import datetime                                #调入时间模块1111
imyear = input("请输入您的出生年份:")         #输入出生年份
nowyear = datetime.datetime.now().year         #计算当前年份
age=nowyear-int(imyear)                        #计算实际年龄
print("您的年龄为:"+str(age)+"岁")            #输出年龄

if age < 18:
    print("您现在为未成年人 (*^_^*)")
elif age >= 18 and age<66:
    print("您现在为青年人 ( ఠൠఠ )ノ")
elif age >= 66 and age<80:
    print("您现在为中年人 ( ̄▽ ̄)")
else :
    print("您现在为老年人(❤ ω ❤)")

# num = input("输入字符:")
# print(num+"的ASCII码为:", ord(num))

Screenshot after running:
Insert picture description here

5. Python loop statement while statement, for statement, when we need to do the same thing repeatedly, we need to think of them:
a.while statement:

i = 1      #创建并初始化一个控制while循环的变量i
while i <= 10:
        print("hello")   #此处执行10次
        i += 1 

Screenshot after running:
Insert picture description here

b.for statement:
Note:
break: jump out of the entire loop, and will not recycle the content behind
continue: jump out of this loop, the code behind continue will not be executed, but the loop will continue
eixt(): end the program

for i in range(10):   #与C语言不同,in后面的数值会赋值给i,循环次数看in后面数据个数,range相当于一个列表list: [0,1,2,3,4,5,6,7,8,9],所以正常会循环十次
    if i == 5:
    #break
    #continue
    exit()
  print(i)
print('hello python')

Examples show:

def xunhuan():                      #加入了一个函数,可以被调用
    for i in  range(1,10,1):
        print(i, end=" ")           #不会换行print(end=" ")

    string1 = ["天甜费", "一飞冲天咻咻"]   #列表
    string2 = "天甜"                #字符串
    for fei in string1:
        print(fei)
    for i in string2:
        print(i)

f = 2 ;
while f >= 1:                       #while 语句演示
    f = f-1
    xunhuan()

Screenshot after running:
Insert picture description here
6. Iterator and generator:
learning URL: iterator and generator learning link
a. Iterator: data structure that can be looped out of for: Python, any object, as long as __next__ party is defined, iter The method in () is an iterator: strings, lists, tuples, dictionaries, and sets are all; dictionaries and sets are unordered, but they can be iterated and verified by themselves, which is very interesting;
b. Generate Generator: In python, this mechanism of calculating while looping is called generator; generator is also a kind of iterator, but you can only iterate it once, because they don’t take all the values Store in memory, but generate values ​​at runtime. The program has a yield/recursive calculation formula: it can be called an iterator
generator. Purpose of existence: save space and share
**generator introduction link: ** yield and return
example display: the first function, the required value is The calculated num = num +1, the memory will be released after yield returns, saving space; and the second function requires all data to be stored in the memory before it can be taken out, wasting memory, both of which will be in When dealing with large amounts of data, you can see the difference. The former will use much less space than the latter, reducing memory pressure:
Insert picture description here
Insert picture description here
7. Module import:
Python, one of the advantages we have introduced before, is that there are many third-party modules. At that time, we said that there are many brothers. , But there are many brothers and no one to help, so a code is defined between the brothers, which means that when you see the code, you will be there:
a.from xxx import xxx
b.import xxx

Note: the module is a function of the package after effects, reference can be a function of their import written. (The process does not need us to go into it now, just understand the usage rules)
Python comes with system modules, you can also import third-party modules (how to import third-party modules will be discussed later), or reference your own modules.
The order in which the system searches for modules, first finds whether there is in the folder, and whether there is in the python environment variable directory, if there are none, an error will be reported:

Example display:
#define a simple module of module.py, the following is the program in the module

#定义一个model.py的简单模块,下面是模块里面的程序
pinetree = '我是一棵松树'        #定义一个全局变量
def fun_module():              #定义一个函数
  pinetree = '挂上彩灯/礼物......我要变成一颗圣诞树\n' #更新变量值
  print(pinetree)

#Define a test module to call the module.py module:

import module                              #引入模块
print('输出全局变量为:',module.pinetree)   #操作变量
module.fun_module()                        #操作函数

Screenshot after running:
Insert picture description here
8. File operation:
a. Open file operation: file = open("D:\abc.txt", r/w/a, encoding ='utf-8') or
with open("D:\ abc.txt", r/w/a, encoding ='utf-8') as file
Note:
#1. "D:\abc.txt": is the absolute path of the file;
#2.r/w/a: It is the mode selection, r: read-only mode, w: write-only mode, a: additional write mode; binary write is followed by b, such as ab;
#3.encoding ='utf-8': encoding mode utf- 8. Universal coding.
b. File writing operation: file.write(string)->Open the file to choose w/a mode;
c. Read file operation: response=file.read()->Open the file to choose r mode;
d. Close File operations: file.close()->After the read and write operations are completed, the file will not be saved until the file is closed.

Examples show:

file = open("D:\\fei.txt","a",encoding='utf-8')
file.write("费")
file.close()

file = open("D:\\fei.txt","r",encoding='utf-8')
File = file.read()
print(File)
file.close()

Screenshot after running:
Insert picture description here
Insert picture description here
9.os: Process files and directories: The
following figure is an introduction to the functions of os operation. You can find it when you need it, and you can practice it when you have time to deepen your understanding and impression. Programming is to keep typing code Just like an athlete, no matter how good you were before, as long as you don’t exercise for a period of time, you will obviously feel a step backward: learning is like riding a boat against the current.

Insert picture description here
10. Exception handling try: exception handling learning link
Exception handling is to put the code that may make mistakes into the following grammar, the most commonly used form:
a.try:
the program that may make mistakes
except the error type (the error type should be selected) :
print("The program went wrong")
b.try:
The program that may make mistakes
except Exception as reason:
print("The program went wrong", reason. __ class __ .__ name__)
finally:
The program that will be executed after the error

Examples show:

a = [1, 2, 3]
try:
    a[3]
except Exception as e:
    print('错误类型是', e.__class__.__name__)
    print('错误明细是', e)
finally:
    print('hello')

Screenshot after running:
Insert picture description here
11. Object: It is said that python is a high-level language, mainly because of object-oriented, then we come to reveal the true face of object-oriented Lushan:

Example: C language is a process-oriented language, that is, to build a house to describe moving bricks, mud, and building walls; python and some other high-level languages ​​are object-oriented languages, that is, only need to describe the length, width, and height styles, etc. A house can be built; after
understanding the above, only the definition of the object is understood. There is still a distance from the actual use:
a. The object is divided into two parts: static and dynamic: attributes (defined variables) and behavior (encapsulated in There can be many functions in a class): A class is a carrier that encapsulates attributes and behaviors, class name is xxx ;

import random as r

class Fish:                 #父类,定义一个鱼:Fish类
    def __init__(self):
        self.x = r.randint(1,10)   #父类,定义2个属性x,y
        self.y = r.randint(1,10)    
    def move(self):
        self.x -= 1
        print("我的位置是:",self.x,self.y)
class Glodfish(Fish):       #子类,定义一个金鱼:GlodFish类,继承Fish父类的方法,下面的其他鱼也是一样的
    pass
class Carp(Fish):         
    pass
class Salmen(Fish):       
    pass
class Shark(Fish):        
    def __init__(self):
        super().__init__() #子类,操作这个语句,就可以使用父类的属性
        #super().__init__派生类(子类)调用基类(父类)的**类属性**,要进行声明;
        self.hungry = True     
    def eat(self):         #子类,定义一个方法
        if self.hungry:
            print("吃货的梦想就是天天有的吃,哈哈")
            self.hungry = False
        else:
            print("太撑了,吃不下了!")
F = Fish()     #父类,实例化(类实例化之后就可以操作属性及方法),比如下面的方式
F.move()
F.move()

S = Shark()      #子类,实例化
print(S.hungry)  #类实例化之后就可以操作属性及方法
S.eat()
S.move()

b. After the object is classed: the class has the characteristics of encapsulation, inheritance, polymorphism, etc., which can make the software design more flexible and can better reuse the code; everything is an object.
c. Define a wild goose, beak, wings, claw attributes; foraging, flying, sleeping and other behaviors -> encapsulation;
d. Quadrilateral (parent class): rectangle, square, parallelogram (subclass) -> inheritance
e. Screws: long screws, short screws -> reflect the object-oriented polymorphic characteristics.

Variable definition in the class: variable transfer, class attribute, instance attribute;

#1.魔术方法__init__()
class Geese:
     def __init__(self,beak,wing,claw):
         print("我是大雁类,我有以下特征:")
         print(beak)
         print(wing)
         print(claw)
beak_1 = "喙的基部比较高,长度和头部的长度几乎相等"
wing_1 = "翅膀长而尖"
claw_1 = "爪子是噗状的"

wildGoose = Geese(beak_1,wing_1,claw_1) #变量传递

#2.创建类属性,指定义在类中,且在方法外面的:
class Geese:
    beak_1 = "喙的基部比较高,长度和头部的长度几乎相等"
    wing_1 = "翅膀长而尖"
    claw_1 = "爪子是噗状的"           #三个类属性,直接定义在类下面
    def __init__(self):
        print("我是大雁类,我有以下特征:")
        print(Geese.beak_1)
        print(Geese.wing_1)
        print(Geese.claw_1)

wildGoose = Geese()

#3.创建实例属性,指定义在类的方法中的属性:
class Geese:
    def __init__(self):                                              #类的方法
        self.beak_1 = "喙的基部比较高,长度和头部的长度几乎相等"
        self.wing_1 = "翅膀长而尖"
        self.claw_1 = "爪子是噗状的"#三个实例属性,定义在 __init__(self)下面
        print("我是大雁类,我有以下特征:")
        print(self.beak_1)
        print(self.wing_1)
        print(self.claw_1)

wildGoose = Geese()

#4.实例属性通过实例名进行修改:
class Geese:
    def __init__(self):
         self.beak_1 = "喙的基部比较高,长度和头部的长度几乎相等"
         self.wing_1 = "翅膀长而尖"
         self.claw_1 = "爪子是噗状的"
         print("我是大雁类,我有以下特征:")
         print(self.beak_1)
         print(self.wing_1)
         print(self.claw_1)

wildGoose1 = Geese()
wildGoose2 = Geese()
wildGoose1.wing_1 = "毛绒绒的"
print(wildGoose1.wing_1)
print(wildGoose2.wing_1)

#5.类里面创建方法:
class Geese:
    def __init__(self):
         self.beak_1 = "喙的基部比较高,长度和头部的长度几乎相等"
         self.wing_1 = "翅膀长而尖"
         self.claw_1 = "爪子是噗状的"
         print("我是大雁类,我有以下特征:")
         print(self.beak_1)
         print(self.wing_1)
         print(self.claw_1)
    def fly(self):
        print("我能飞")

wildGoose1 = Geese()
wildGoose1.fly()


#6.重写父类方法
class Fruit:
    color = "绿色"
    def harvest(self,color):
        print("水果是:"+color+"的")
        print("水果原来是:"+Fruit.color+"的")
class Orange(Fruit):
    color = "橙色"
    def __init__(self):
        print("我是橙子")
    def harvest(self,color):
        print("橙子是::" + color + "的")
        print("橙子原来是:" + Fruit.color + "的")

#7.派生类中调用基类__init__()
class Fruit:
     def __init__(self,color = "绿色"):
         Fruit.color = self.color
     def harvest(self):
         print("水果原来是:"+Fruit.color+"的")
class Orange(Fruit):
     color = "橙色"
     def __init__(self):
         super().__init__()
         print("我是橙子")

orange = Orange()
orange.harvest()

The above is the learning of the basic knowledge part. I have made a basic arrangement and summary here, but if you want to be an excellent big cow, you must continue to learn knowledge, learn endlessly, and enter the pit.

I’ve heard a sentence before and I feel good, I must teach people what I learn, and give people what I earn. This is also my original intention to do this, because when I encounter a BUG or a knowledge point I don’t know, I go to Baidu Searching can always find methods or ideas, so I also want to contribute my meager strength.

The third part of sharing, continuing to update,,,,, *

Guess you like

Origin blog.csdn.net/weixin_46008828/article/details/108566094