Study notes about Python

First Acquaintance------------------------------------------------ ---------

Data Types and Variables

字符串(string) //‘pork’    ‘辣椒’
数字(number)   // 0.5        5
列表           //['盐','芝麻','花椒'] 	
字典           //{'name':'王伟','age':25,'school':'新东方'}
逻辑(Bool)     //True(真)   False(假)

变量   //变量可以变化,存放不同的东西
       //pot   = ‘辣椒’    listBox   =  ['盐','芝麻', '花椒']

process control

Judgment statement (if)

if(fire == '大火'):  #注意有冒号
  print('翻炒10下')  #注意冒号下的分支程序要 Tab键缩进
else:       
  print('翻炒20下')	

Branch judgment statement (if...elif...else)

age=12;            #//要顶格写
if(age<18):        #//true  逻辑成立为真
  print('未成年'); #//注意要有缩进
else:              #//false 逻辑不成立为假
  print('成年');

#//注意: python里无switch

a =1;
#a =0;
a ='lili';
#a ='';
a ={
    
    'name':'lili'};
#a ={};
if(a):  #//真的 True  非零数字 非空字符串 非空对象
  print('真');
else:   #//假   False 数字零   空字符串 空对象;  
  print('假');

Loop statement (for/while)

count=0
while(count<10): 
  count = count+1	
  print('翻炒'+str(count))
for i in range(1, 10):
    for j in range(1, i + 1):
        print('{}*{}={} '.format(i, j, i * j), end='')  #//end指定结束方式,如不指定,将默认换行
    print('') 

#//遍历对象元素	
box = ['banana', 'apple',  'book']
for e in box:   
   print(e);#列表查找到打印后续,如果是字典则打印对应的键值,如果查找无结果就遍历全部
   
for x in 'Python':  #//遍历
   print(x); 
   
#遍历一个数字序列
for i in range(5):
  if(i==2):
    break;      #//跳出终止整个循环
    #//continue;  跳过本次循环,继续下一次循环
  print(i);

#找出偶数值
for num in range(2, 10):
    if num % 2 == 0:
        print("找到一偶数:", num)
    continue

function

define function (def)

def do_xcr():
    print("hello world")
    print("准备食材")
    print("炒菜完成")

Call functions

do_xcr()
do_xcr()
do_xcr()

class (similar to struct)

class Person:     #//定义类(只是想法)
  name = 'lili'   #//类属性
  def talk(self): #//类行为(方法):形参self必须有,代表类的实例
    print("can talk,my name is:",self.name);

p = Person()      #//新建类的实例对象
p.talk()          #//调用对象的方法(无参,但其实有参,它是隐藏的第一个实参,为类的实例)
print("name is",p.name)  #//访问对象的属性	
p.age=30          #//可动态添加(python是动态语言)
print("new age is",p.age)

library (import)

#//官方文档  https://docs.python.org/zh-cn/3/ 
import random #//随机数库
print(random.random())

import time; #//时间的库
print(time.ctime())
     
import math; #//数学库
print(math.gcd(4,12));

from time import sleep, ctime//import the sleep and ctime functions in the time function library

input/output (input/print)

a = input("请输入: ")
print(a, type(a))

print('%s %d %c %x'%('ivan',10,65,15))  #//老版本格式化输出: 字符串 整型 字符 16进制

i = 2
j = 5
print('{}*{}={} '.format(i, j, i * j))	

#//新版格式化输出: 0指format的第一个对象(如3),1指format的第二个对象(如10), 
#//                {1:x} 冒号前指对象,冒号后指定输出类型(b:二进制,x:16进制)	
print('{0}二进制:{0:4b} {1}十进制:{1:d} 16进制:{1:x}'.format(3,10)) 

exception (try)

x=3
y=0
try:    #//如无异常判断将终止退出,不能继续往下执行
    print(x/y)
except : 
    print("can not be zero")	
print("go go go")

grammar

#//---关键字(保留字)   -->  保留字不能用作常数或变数,或任何其他标识符名称 ,python 关键字全小写 
print  pass assert
if else  return for while continue break
class try   
def with 	import from is finally lambda 
= + - * %	  
#//---语句
counter = 100;  #//语句:把整型数据100赋值给变量counter (;表示语句结束,可省略).  
name = "John"   #//字符串类型
price = 2+3+5;  #//表达式语句 
Price = 8;      #//区分大小写(price 和Price不是同一个)
#//---注释
#                    #//单行注释 
'''  多行注释 '''    #//多行注释:三个单引号或双引号
"""  多行注释 """     

#//---字面量(直接量)  -->  直接用的数据值(如 print(34+5))
34 'ivan' True False #//基础类型: 数字 字符串 bool值。  
[2,3,'ivan',5]       #//列表 train= [2,5,'ivan',False]   
                     #//print(train)  train[2]=55 print(train) 
(1,5)                #//元祖     a=(1,5)   a[0]=3; 改写会失败   
{
    
    'name':'lili','age':30} #//字典 b={'name':'lili','age':30}; b['age']=20;
	                 #//print(b);  print(b['name']);

The literal quantity is, for example, int a = 1; this 1 is the literal quantity, a is the variable name,
and String b = "abc"; this abc is the literal quantity, and b is the variable name

Variables and data types ---------------------------------------------- -----------

variable definition assignment

age =3;           #//变量赋值(实现,获得空间)
                  #//1age =5;   (报错 命名:数字不能在前)               
name = 'ivan';    #//变量赋值字符串类型
girl = {
    
    'name':'lili','age':30}; #//变量赋值字典类型
a,b=1,2;          #//多重赋值, 拆解为  a=1;  b=2; 
a = b = 1;        #//连续赋值, 拆解为  a=1;  b=1; 

basic data type

number: number (integer floating point complex number)

a,b,c = 10,3.14,1+2j  
print(a,b,c)
print(a+c) 
print(c,type(c))

string

str = 'hello baby'; 
print(str,str[1],str[2:4],str[6:]);

composite data type

List object (upgrade array: place any type of data)

train = [50,20,'apple'];
print(train);
list = train;
train[2] = 'tv';
print(train);
print(list);

tuple object (read-only array [no modification])

tuples = (1,6,'ivan',3,'good',77);
print(tuples);       #//输出 (1,6,'ivan',3,'good',77)
print(tuples[1]);    #//输出 6
print(tuples[1:3]);  #//输出 (6, 'ivan')   
	
tuples[1]=2;        #//报错,元祖是禁止修改的			

tu2 =(56,'yzg',3)
print(tuples+tu2)   #//拼接

print(tuples[2.0])  #//报错:TypeError: tuple indices must be integers or slices, not float 
                    #原因时类型不匹配,需把2.0  转为int 用 int(2.0)

Collection objects (internal unordered/non-repeated)

basket = {
    
    'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket);#打印不重复
print('banana' in basket);#只能返回有无,不能返回序号

Dictionary object (key-value pair)

man={
    
    'name':'ivan','age':30};
print(man);
obj={
    
    };  #//定义空的字典对象
obj['name']='yzg';
obj['age']=28;
print(obj['name'],type(obj));
man = obj;
obj['age'] =10;
print(man);

Space allocation (reference address)

str1 = "ivan";
str2 = str1;    #//赋值是 引用的拷贝(引用是指向实体的地址)
print(id(str1)) #//id() 是查看对象的存储地址
print(id(str2))
print('str1 = ' + str1);  
print('str2 = ' + str2); 	
str1 = "yzg";
print(id(str1))
print(id(str2))

Nested references (reference addresses)

train = [50,20,'apple'];
train[1] ={
    
    'name':'lili','age':30}
print(train)


#//可把函数名,看成指向代码块的引用
def gogo():
    print("i can gogogo")
    
train[1]['teach']=gogo  
print(train)
train[1]['teach']()

Data operation

Arithmetic (+ - * ** / % modulo (remainder) **** power // divide by integer)

print(6+3*5/2); 
#//---浮点型精度问题(因二进制,0.333表示有问题)运算中有0.3出现都会有问题
print(0.3-0.2);             #输出0.099  
print(0.1+0.2==0.3);        #输出 false
#//解决方法:放大后再缩小
print((10*0.1+10*0.2)/10==0.3); #输出 true 
#//---% 取模(求余)
print(3%2);  #单双数判断

#//---优先运算加 ()  
print((10+20)/2);  

print(2**3);  #//2的3次方(幂)
print(9//2);  #//取整除 为4

Assignment operation (= += -= *= /= %= **= //=)

a=2; 	 
a+=3 	  #//与 a = a+3; 相同
print(a); 
a%=2;     #//与 a = a%2; 相同
print(a);    
a**=3
print(a);    
a = 9; 
a//=4
print(a); 

compare(<> <= >= == !=)

age =18;
if(age>=18):
  print('成年');

today ='11.10';
if(today!='11.11'):
  print('双11还未到');

a=2;
b='2';
if(a==b):
  print('值相等');

Bit operation (& and | or ~ not ^ XOR << left shift >> right shift)

a=60 #//对应二进制00111100
b=13 #//对应二进制00001101
print(a&b)    # 00001100
print(a|b)    # 00111101
print(a^b)    # 00110001
print(~a)     # 11000011
c=4           # 00000100
print(c<<1)   # 00001000
print(c>>1)   # 00000010

Logical operations (and and or or not in not in is is not)

age =25;
print('是青年吗 ',(age>18 and age<30));

hasHouse,money =True,1000;
#hasHouse,money =False,1000;
if(hasHouse or money>1000000):
  print("有房或有100万,嫁给他")

if not(hasHouse or money>1000000):
  print("即没房也没100万,不嫁")

list = [1,2,3,4,8];
print('3在list中吗',3 in list);
print('6不在list中吗',6 not in list);

lili = {
    
    'name':'lili','age':30};
x = lili;
x['name']='linda';
print(x,'是lili这个人吗',x is lili);

type conversion

#//int() 转换为整型数字 	
print(int(3.14)+2);	
print(int('12')+5);
print(int(0xa)+3); 
#//转float
print(float(3)+1.24);		
#//str() 转换为字符串    
print(str('12')+'5');

lili = {
    
    'name':'lili','age':30};
print(str(lili)+'good');
print(lili+'good'); #fail  	

#//隐式转换(自动转换)   
name = 'ivan';  print(name[1]); #//字符串转换为列表 --> 查找某位置的字符
print( '7'+'people');           #//数字转换为字符串	--> 进行拼接
print( '7'-'people');           #//报错:隐式转换失败 

function------------------------------------------------- --------

(A logical code block describing how to do things -> encapsulation (hidden reuse))

first acquaintance

definition statement

#//关键字:def                --  让系统识别 这是函数
#//函数名: start              --  名字 (事情的名称, 注: 定义多个函数时名字不能相同)
#//函数体:冒号后缩进的代码块 --  内容(描述事如何做)
def start():   # 定义(规划做什么事)                
  print('starting... machine ');
  print('start success');

transfer

start();  #调用(开始做事)
start();  #可调用多次 (封装隐藏 --> 复用)

pass parameters

def start(name): #//函数参数: ()  --  输入(做事需要什么东西, 如 name)             
  print('start '+ name +' success');		           

start('iphone');
start('pad');

def start2(n): #//形参 n (相当于局部变量)
  #//n = a;  参数n 相当于局部变量,
  print('start '+ n +' success');	
a ='iphone';
start2(a);    #//函数传参, 类似于变量的赋值   n = a;,把实参赋值给形参

function scope

def fn():  
  age=35;  #//局部变量
  print('in fn age= ', age);
fn();
print('age =',age);  #//报错,外面不能访问里面变量

definition statement

Empty function (pass//vacancy)

def sum(n): #//空函数
  pass      #//占位,什么也不做
sum();

Named function (def//keyword)

//关键字:def                --  让系统识别 这是函数
//函数名: start              --  名字 (事情的名称, 注: 定义多个函数时名字不能相同)
//函数体:冒号后缩进的代码块   --  内容(描述事如何做)
def start(): #//函数声明定义(规划做什么事)  
  print('starting... machine ');
  print('start success');

start();     #//函数调用(开始做事)
start();     #//可调用多次 (封装隐藏 --> 复用)       
fn = start;  fn();  #//函数名赋值给变量,可间接调用

Do the method in the object (the function is introduced into the object)

Do the behavior (method) in the class

class Person:
  name = 'ivan'
  def speak(this):
    print(this.name,'can speak');
    
ivan = Person();
ivan.speak();

make a value in the dictionary

def fn():
  print('driver bus');  
person ={
    
    
  'name':'ivan',
  'driver':fn
}

person['driver']();

Parameter passing (function input port)

person = {
    
    
 'name':'yzg',
 'age':30
}

def changeName(p):   #//局部变量 p = person  (person里存放的是引用地址 如028)
  p['name'] = 'ivan';

changeName(person);
print(person);

String/Number/Boolean ----->Pass parameters

x = 'iphone';  #//或x = 30 , x = true;
def fn(v):     #//函数参数: ()  --  输入(做事需要什么东西, 如 v) 
  print(v,' type: ',type(v));
  v = 'android';
fn('iphone');  #//传字符串(或 数值6000 布尔值) 
print(x);

List -----> pass parameters

a = ['ivan','yzg','lili']
def change(addr):
	addr[1]='wangwei';
change(a);
print(a);

Function -----> pass parameters (callback function)

def fn(callback): #//函数参数: ()  --  输入(做事需要什么东西, 如 callback) 
  print(callback,' type:',type(callback));
  callback();    #//通过参数,间接调用函数 (回调函数)       

def start():
  print('start tv');

fn(start);  #//函数做参数传入

Dictionary object -----> parameter passing

f car(): print(' dirver car');  #//需先定义,后再使用
def bus(): print(' dirver bus');

person ={
    
    
  'name':'ivan',
  'driver':car      
}

def change(obj):
  obj['name']='yzg';   #//更改对象的属性
  obj['driver']= bus;  #//更改对象的方法

change(person);
print(person['name']);
person['driver']();

Class object -----> parameter passing

class Animal:  #//定义对象 Animal
  name = "animal";
  def breath(this):
    print("can breath from water");

def air():
  print("breath from air");
def change(o):
  print("after change");
  o.breath = air;

obj =  Animal(); #//新建对象实例
print(obj.name);
obj.breath();
change(obj);     #//对象做实参(引用类型传递 是地址传递,指向的是同一实体)
print(obj.name);
obj.breath();

Indefinite parameters (brought into Yuanzu dictionary)

*args The incoming parameter is a tuple type

def test(*args):    
    print(args)   
    for i in args:
        print(i)

test(1,2,3)

The parameter passed in by **kwargs is a dict type

def test(**kwargs):
    print(kwargs)
    keys = kwargs.keys()    #获取键名
    value = kwargs.values() #获取键值
    print(keys)
    print(value)

test(a=1,b=2,c=3,d=4)

**Accumulation of multiple numbers

def sum(*args):    #//args里存放了所以的实参
    ret = 0;
    for obj in args:
        print(obj);
        ret += obj;
    print('sum is', ret);
    return ret;

sum(1);
sum(1, 4, 3);

Return value (return)

return number string

def sum(x, y):
    return x + y; #// 函数返回值:return --  输出(做完事后能得到什么)
                  #// 注:无return时,返回None,  return 后面语句不执行
print(sum(3, 5)); #// 传参调用

return function

def fn(a):
  print('fn run');
  def fnn(b):
    print('fnn run ..');
    return a+b;
  return fnn;
print(fn(10)(20));

scope (local global)

country = 'china'; #// 全局变量(任意地方用)

def fn():       #// 函数作用域分函数内外
    country = 'yindu';
    age = 35;    #// 局部变量
    print('fn: ', country);
    print('fn: ', age);
    def fn1():  #//局部函数
        print('fn1 go ');

print(country);
fn();
print(age); #// 不能访问函数内部资源, 故报错NameError::age is not defined
fn1(); #// 局部函数不能访问

scope chain

Function nesting --> Form a chain --> Variable backtracking (currently not available, trace the previous home along the chain)

name = "first";
def fn1():
    name = "second";
    def fn2():
        print(name); #// 变量回溯(当前没有,追查上家)
    fn2();
    print(name);

fn1();
print(name);
fn2(); #// fn2是局部函数,不能访问

Example: The following program output information is

country='china';  #//全局变量(任意地方用)
age =80;
def fn():
  country = 'yindu';
  print('2 level country is ',country);
  name1 = 'ivan';  #//局部变量(只能在函数内部用)
  age =30;      #//同名时,在局部作用域内(函数内),局部变量有效。

  def fn():      #//嵌套子函数
    print('3 level name is ',name1);  #//子函数可用父函数作用域内的变量 
    age =8;
  fn();
  print('2 level age is ',age);
fn();
print('1 level age is ',age);    #//80 同名时:函数外,全局变量的有效 
print('1 level name is ',name1); #//不能访问局部变量 NameError: name 'name1' is not defined

Example: The following program output information is

i=0;
def fn1(i):
  print( 'i = ',i);

a = [1,2,3];
def fn(callback):
  for i in range(3):
    a[i] = callback;
  callback(i);
fn(fn1);
a[0](i);#由fn(fn1)后 a[]代指fn1
a[1](i);

Functional programming (map-oriented)

Imperative programming (process-oriented): care about execution steps, there are variables, expressions, control statements, etc. -> solution steps (tell the machine how to do it)
meta-programming (object-oriented): take objects (independent individuals) as the core, organize data and Relationship -> find objects (tell the machine who did it)
functional programming (map-oriented): calculate like a mathematical function (expression), without changing state and data -> mapping relationship (tell the machine what to do)

不变性(没有可变的状态,不依赖也不改变外面状态,引用透明,和没有副作用)
适合并发编程(没有状态的上锁) 
当把函数也看成数据,输入确定,输出也确定 -> 无状态化(因为一旦独立投入计算,我们没有和其他人同步的要求了)

Anonymous functions (lambda intermediate processing does not need to be named)

fn = lambda x:x+10;  #//创建匿名函数lambda,让变量fn 指向它
	             #//lambda:冒号 左侧表示函数接收的参数x ,右侧表示函数的返回值x+10
	             #//等价于 def fn(x):return x+10
print(fn(1));
print((lambda x:x+10)(3)) #//可定义调用一气完成

c = lambda x,y=2: x+y    //默认值
print(c(10))	

L = [(lambda x: x**2),(lambda x: x**4)]  //字典中
print(L[0](2),L[1](2));
print((lambda x,y: x if x> y else y)(3,5))  //求最值(类三目运算)

object oriented

class Actor:       #//定义类(只是想法)
  name = '赵丽颖'  #//类属性
  age  = 35
  def act(self):   #//类行为(方法):形参this必须有,代表类的实例
    print(self.name," 会演戏")
  def sing(self):
    print(self.name," 会唱歌")

obj = Actor() #//创建类的实例对象 
print(obj.name) #//访问对象的属性
print(obj.age)
obj.act()     #//调用对象的方法(无参,但其实有参,它是隐藏的第一个实参,为类的实例)	
obj.sing()    

#//动态语言:可动态添加属性和方法(python是动态语言,不像c++静态语言,定义完后,后面不能修改)
obj.addr="成都"  #//动态添加属性
print(obj.addr)

def show(self):
    print(self.name,self.age,self.addr);

obj.show = show; #//动态添加方法
obj.show(obj) #//动态添加的要传入对象势力,不能隐藏
obj.sing() 	

inherit

class Animal:      #//定义类(只是想法)
  name = 'animal'  #//类属性
  def eat(self):   #//类行为(方法):形参self必须有(类似this),代表类的实例
    print(self.name," can eat")
  def breath(self):
    print(self.name," can breath")
  def run(self):
    print(self.name," can run")	

#//父类:通常是抽象出来的

Inheritance: Reuse (no need to rewrite the parent class method)
Extension: The subclass Cat can derive new capabilities based on the ability to inherit the parent class Animal’s ability to eat and run, such as catchMouse Hidden
: the subclass will block the method of the same name of the parent class

use of classes

Default processing to solve exception error

c = Cat()  #//新建类的实例对象c 
c.catchMouse()
c.breath()
c.run()

f = Fish() #//新建类的实例对象f 
f.eat();
f.breath('water');
f.swim();
f.breath();   #//会报错参数个数不匹配,因子类会隐藏了父类的同名函数, 
              #//1.用默认参数解决
              #//def breath(self,str='water')  
	      #//   print(self.name," can breath from ",str)	
	      #//注意:用重载不行,下面的同名函数会覆盖上面的同名函数,不会智能匹配参数个数
              #//2.用不定参  

polymorphism (futurity)

Python is inherently polymorphic (dynamic language, dynamic binding at runtime)

def play(obj):    
  obj.breath()  #//使用者在不知道具体对象情况下,直接掉接口breath. 
                #//breath会根据对象做调整

play(c);   
play(f); 

Constructor destructor (initialization of the class)

class Line:
  name='a line'
  def __init__(this,len=3): #//可选,无时,会有默认的
    this.length = len
    print('构造函数运行')
  def __del__(this): #//可选,无时,会有默认的
    print('析构函数运行,释放资源')
  def show(this):
    print('length is',this.length);


obj = Line() #//创建对象实例时,自动调用构造函数。
obj.show();  #//执行完自动析构(引用计数方式,进行垃圾回收)

Permissions (naturally fully open)

Problem set:
why there is printing information when there is no printing

insert image description here

To be verified:
box = ['banana', 'apple', 'book']
for e in box:
print(e); #After the list is found and printed, if it is a dictionary, print the corresponding key value, if there is no result, then traverse all

Guess you like

Origin blog.csdn.net/weixin_49048045/article/details/122451085