Primer conocido ------------------------------------------------ ---------
Tipos de datos y variables
字符串(string) //‘pork’ ‘辣椒’
数字(number) // 0.5 5
列表 //['盐','芝麻','花椒']
字典 //{'name':'王伟','age':25,'school':'新东方'}
逻辑(Bool) //True(真) False(假)
变量 //变量可以变化,存放不同的东西
//pot = ‘辣椒’ listBox = ['盐','芝麻', '花椒']
control de procesos
Declaración de sentencia (si)
if(fire == '大火'): #注意有冒号
print('翻炒10下') #注意冒号下的分支程序要 Tab键缩进
else:
print('翻炒20下')
Sentencia de juicio de rama (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('假');
Instrucción de bucle (para/mientras)
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
función
definir función (def)
def do_xcr():
print("hello world")
print("准备食材")
print("炒菜完成")
Funciones de llamada
do_xcr()
do_xcr()
do_xcr()
clase (similar a estructura)
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)
biblioteca (importación)
#//官方文档 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//importar las funciones sleep y ctime en la biblioteca de funciones de tiempo
entrada/salida (entrada/impresión)
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))
excepción (intentar)
x=3
y=0
try: #//如无异常判断将终止退出,不能继续往下执行
print(x/y)
except :
print("can not be zero")
print("go go go")
gramática
#//---关键字(保留字) --> 保留字不能用作常数或变数,或任何其他标识符名称 ,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']);
La cantidad literal es, por ejemplo, int a = 1; este 1 es la cantidad literal, a es el nombre de la variable
y String b = "abc"; este abc es la cantidad literal y b es el nombre de la variable
Variables y tipos de datos ---------------------------------------------- -----------
asignación de definición de variable
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;
tipo de datos básicos
número: número (número complejo de punto flotante entero)
a,b,c = 10,3.14,1+2j
print(a,b,c)
print(a+c)
print(c,type(c))
cadena
str = 'hello baby';
print(str,str[1],str[2:4],str[6:]);
tipo de datos compuesto
Objeto de lista (matriz de actualización: coloque cualquier tipo de datos)
train = [50,20,'apple'];
print(train);
list = train;
train[2] = 'tv';
print(train);
print(list);
objeto tupla (matriz de solo lectura [sin modificación])
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)
Objetos de colección (internos desordenados/no repetidos)
basket = {
'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket);#打印不重复
print('banana' in basket);#只能返回有无,不能返回序号
Objeto de diccionario (par clave-valor)
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);
Asignación de espacio (dirección de referencia)
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))
Referencias anidadas (direcciones de referencia)
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']()
operación de datos
Aritmética (+ - * ** / % módulo (resto) **** potencia // dividir por entero)
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
Operación de asignación (= += -= *= /= %= **= //=)
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);
comparar(<> <= >= == !=)
age =18;
if(age>=18):
print('成年');
today ='11.10';
if(today!='11.11'):
print('双11还未到');
a=2;
b='2';
if(a==b):
print('值相等');
Operación de bit (& y | o ~ no ^ XOR << desplazamiento a la izquierda >> desplazamiento a la derecha)
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
Operaciones lógicas (and and or or not in not in is not 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);
conversión de tipo
#//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'); #//报错:隐式转换失败
función------------------------------------------------- --------
(Un bloque de código lógico que describe cómo hacer las cosas -> encapsulación (reutilización oculta))
primer conocido
declaración de definición
#//关键字:def -- 让系统识别 这是函数
#//函数名: start -- 名字 (事情的名称, 注: 定义多个函数时名字不能相同)
#//函数体:冒号后缩进的代码块 -- 内容(描述事如何做)
def start(): # 定义(规划做什么事)
print('starting... machine ');
print('start success');
transferir
start(); #调用(开始做事)
start(); #可调用多次 (封装隐藏 --> 复用)
pasar parámetros
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;,把实参赋值给形参
alcance de la función
def fn():
age=35; #//局部变量
print('in fn age= ', age);
fn();
print('age =',age); #//报错,外面不能访问里面变量
declaración de definición
Función vacía (aprobado//vacante)
def sum(n): #//空函数
pass #//占位,什么也不做
sum();
Función nombrada (def//palabra clave)
//关键字:def -- 让系统识别 这是函数
//函数名: start -- 名字 (事情的名称, 注: 定义多个函数时名字不能相同)
//函数体:冒号后缩进的代码块 -- 内容(描述事如何做)
def start(): #//函数声明定义(规划做什么事)
print('starting... machine ');
print('start success');
start(); #//函数调用(开始做事)
start(); #//可调用多次 (封装隐藏 --> 复用)
fn = start; fn(); #//函数名赋值给变量,可间接调用
Hacer el método en el objeto (la función se introduce en el objeto)
Hacer el comportamiento (método) en la clase
class Person:
name = 'ivan'
def speak(this):
print(this.name,'can speak');
ivan = Person();
ivan.speak();
hacer un valor en el diccionario
def fn():
print('driver bus');
person ={
'name':'ivan',
'driver':fn
}
person['driver']();
Paso de parámetros (puerto de entrada de función)
person = {
'name':'yzg',
'age':30
}
def changeName(p): #//局部变量 p = person (person里存放的是引用地址 如028)
p['name'] = 'ivan';
changeName(person);
print(person);
Cadena/Número/Booleano ----->Pasar parámetros
x = 'iphone'; #//或x = 30 , x = true;
def fn(v): #//函数参数: () -- 输入(做事需要什么东西, 如 v)
print(v,' type: ',type(v));
v = 'android';
fn('iphone'); #//传字符串(或 数值6000 布尔值)
print(x);
Lista -----> pasar parámetros
a = ['ivan','yzg','lili']
def change(addr):
addr[1]='wangwei';
change(a);
print(a);
Función -----> pasar parámetros (función de devolución de llamada)
def fn(callback): #//函数参数: () -- 输入(做事需要什么东西, 如 callback)
print(callback,' type:',type(callback));
callback(); #//通过参数,间接调用函数 (回调函数)
def start():
print('start tv');
fn(start); #//函数做参数传入
Objeto de diccionario -----> paso de parámetros
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']();
Objeto de clase -----> paso de parámetros
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();
Parámetros indefinidos (traídos al diccionario Yuanzu)
*args El parámetro entrante es un tipo de tupla
def test(*args):
print(args)
for i in args:
print(i)
test(1,2,3)
El parámetro pasado por **kwargs es un tipo dict
def test(**kwargs):
print(kwargs)
keys = kwargs.keys() #获取键名
value = kwargs.values() #获取键值
print(keys)
print(value)
test(a=1,b=2,c=3,d=4)
**Acumulación de números múltiples
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);
Valor de retorno (retorno)
cadena de número de retorno
def sum(x, y):
return x + y; #// 函数返回值:return -- 输出(做完事后能得到什么)
#// 注:无return时,返回None, return 后面语句不执行
print(sum(3, 5)); #// 传参调用
función de retorno
def fn(a):
print('fn run');
def fnn(b):
print('fnn run ..');
return a+b;
return fnn;
print(fn(10)(20));
alcance (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(); #// 局部函数不能访问
cadena de alcance
Anidamiento de funciones --> Formar una cadena --> Retroceso variable (actualmente no disponible, rastrear el inicio anterior a lo largo de la cadena)
name = "first";
def fn1():
name = "second";
def fn2():
print(name); #// 变量回溯(当前没有,追查上家)
fn2();
print(name);
fn1();
print(name);
fn2(); #// fn2是局部函数,不能访问
Ejemplo: La siguiente información de salida del programa es
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
Ejemplo: La siguiente información de salida del programa es
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);
Programación funcional (orientada a mapas)
Programación imperativa (orientada a procesos): cuidar los pasos de ejecución, hay variables, expresiones, declaraciones de control, etc. -> pasos de solución (decirle a la máquina cómo hacerlo) metaprogramación (orientada a objetos): tomar objetos (individuos
independientes ) como el núcleo, organizar datos y relaciones -> encontrar objetos (decir a la máquina quién lo hizo)
programación funcional (orientada a mapas): calcular como una función matemática (expresión), sin cambiar el estado y los datos -> relación de mapeo (decir al máquina qué hacer)
不变性(没有可变的状态,不依赖也不改变外面状态,引用透明,和没有副作用)
适合并发编程(没有状态的上锁)
当把函数也看成数据,输入确定,输出也确定 -> 无状态化(因为一旦独立投入计算,我们没有和其他人同步的要求了)
Funciones anónimas (no es necesario nombrar el procesamiento intermedio lambda)
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)) //求最值(类三目运算)
orientado a objetos
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()
heredar
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")
#//父类:通常是抽象出来的
Herencia: reutilización (no es necesario volver a escribir el método de la clase principal)
Extensión: la subclase Gato puede derivar nuevas capacidades basadas en la capacidad de heredar la capacidad de comer y correr de la clase principal Animal, como atrapar ratón Oculto: la subclase bloqueará
el método de el mismo nombre de la clase padre
uso de clases
Procesamiento predeterminado para resolver el error de excepción
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.用不定参
polimorfismo (futuro)
Python es inherentemente polimórfico (lenguaje dinámico, enlace dinámico en tiempo de ejecución)
def play(obj):
obj.breath() #//使用者在不知道具体对象情况下,直接掉接口breath.
#//breath会根据对象做调整
play(c);
play(f);
Constructor destructor (inicialización de la clase)
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(); #//执行完自动析构(引用计数方式,进行垃圾回收)
Permisos (naturalmente completamente abiertos)
Conjunto de problemas:
por qué hay información de impresión cuando no hay impresión
Para ser verificado:
box = ['banana', 'apple', 'book']
for e in box:
print(e); #Después de encontrar e imprimir la lista, si es un diccionario, imprima el valor clave correspondiente, si no hay resultado, entonces recorrer todo