python

day02>>>
https://www.cnblogs.com/alex3714/articles/5717620.html
day03>>>
https://www.cnblogs.com/alex3714/articles/5740985.html
day04>>>
https://www.cnblogs.com/alex3714/articles/5765046.html

2018/11/16
python擅长:
web开发:Django,pyramid,Tornado,Boottle,Flask,WebPy
网络编程:Twisted,Requests,Scrapy,Paramiko
科学运算:SciPy,Pandas,Iphython
GUI图形开发:wxPython,PyQT,Kivy
运维自动化:OpenStack,SaltStack,Ansible,腾讯蓝鲸

20k,硅谷,15w美元,语言排名,拉钩网,旧金山,无人运维
算法才是计算机的精髓,自动化开发

学好了PYTHON之后,还是建议你学习下C++,毕竟相比python这个动态语言来讲,C++的效率还是高很多的,但对新手来讲,不建议做为第一门语言开始学习, 为什么呢?打击自信心。。。。呵呵,你懂的

文章:
http:3060674.BL
普通运维人员就是秋后的蚂蚱
http://blog.51cto.com/3060674/1598255
http://blog.51cto.com/3060674/1590803

运维会了开发后可以干什么?
帮助公司开发各种自动化工具
帮助评估和优化业务技术架构
开发公司的内部办公系统,CRM,网站等
做个全栈工程师,全栈就是指什么都能做的样子

毕业后可以开发自动化运维平台,监控,CMDB,Docker\Openstack\Zabbix等开源软件二次开发,WEB聊天软件,BBS,博客,企业网站等

毕业学员,课程掌握
70% 工资10k起 作业B
80% 12k起 作业B+
100% 15k起 作业A

时间9:30-晚6:30

第5章

动态语言和静态语言
动态:不用先声明字符类型
静态:必须先声明字符类型

python优缺点:
优点:
1.简单
2.强大第三方库
3.可移植性强
4.可扩展性-解释性语言 暴露源代理
5.可嵌入性,被其他语言嵌入

缺点:
1.速度慢
2.代码不能加密 解释性明文
3.线程不能利用多cpu问题

python解释器
当我们编写python代码时,我们得到的是一个包含python代码的以.py为扩展名的文本文件。要运行代码,就需要python解释器去执行.py文件。
Cpython:C语开发的,最广泛
Ipython
PyPy:提高速度
Jpython:
IronPython:.NAT平台上

python发展史:
89年诞生
99年才有外部框架
1.0:
2.0:加入内存回收机制,构成了现在Python语言框架的基础
2.4:目前最流行的web框架Django诞生 go语言
2.5:2006
2.6:2008 兼容2.4,3.0
2.7:2010 过渡版本
3.0:2008 不兼容2.4
...
3.5
3.6
3.7
in summary: python2.x
版本区别:
python2.x:不支持写中文
python3.x:可以直接写中文,unicode support
库改变了。(twisted不支持3.0,全变成异步)
什么是计算机语言
语言:人与人之间
计算机语言:人与计算机 C,C++,java,PHP,python
计算机语言历史:
第一代语言:
打孔机--纯机器语言
第二代语言
汇编
第三代语言
C,Pascal,Fortran面向对象的语言
C++面向过程/面向对象编程
java跨平台的纯面向对象的语言
.NET跨语言的平台
字符编码
计算机语言01010101(26个英文字母,加上特殊字符一共需要125个,剩下130个为保留字符)
ASCII 8位 255 1bytes。美国标准信息交换代码 让数字代表一个字符。
-->1980 GB2312,7xxx多个汉字。
-->1995 GBK1.0 2w+
-->2000 GB18030 27xxx
-->Unicode 2bytes 16位,比ASCII占用一倍,字符占用多,兼容其他编码
-->utf8,en:1bytes,zh:3bytes 可变长的字符集,存的ASCII码格式。UTF-8是Unicode的实现方式之一
python2:ASCII,
python3:Unicode 默认支持中文

使python2支持中文:
#-*- coding:utf-8 -*-
name = "曾彩"
print(name)

计算机语言的区别
解释性语言和编译型语言
计算机是不能识别高级语言的, 所以当我们运行一个高级语言程序的时候,就需要一个“翻译机”来从事把高级语言转变成计算机能读懂的机器语言的过程。这个过程分两类,第一种是编译,第二种是解释。
编译型语言:
在程序执行之前,先会通过编译器对程序执行一个编译的过程,把程序转变成机器语言,运行时就不需要翻译,而直接执行就可以了,最典型的例子就是C语言。
解释性语言:
就是没有编译的过程,而是在程序运行的时候,通过解释器对程序执行一个编译的过程,把解释器对程序逐行作出解释,然后直接运行,最典型的例子就是Ruby。

java:先编译后解释的语言,javac通过编译器编译成.class字节码文件,再执行通过解释器给解释成机器文件。
python:解释性语言,把代码解释一句执行一句,但是也有编译过程(PyCodeObject和.pyc文件)。
PyCodeObject是Python编译器真正编译成的结果,当Python程序运行结束时,Python解释器将PyCodeObject写到.pyc文件中。当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则重复上面的过程。
所以pyc文件其实是PyCodeObject的一种持久化保存方式。
历史:
java历史:
SUN公司开发
95年SUN开发JDK1.0
2010甲骨文收购SUN公司
python发展史:
89年诞生,创始人Guido van Rossum
99年才有外部框架
1.0:
2.0:加入内存回收机制,构成了现在Python语言框架的基础
2.4:目前最流行的web框架Django诞生 go语言
2.5:2006
2.6:2008 兼容2.4,3.0
2.7:2010 过渡版本
3.0:2008 不兼容2.4
...
3.5
3.6
3.7

开发工具:
java:eclipse;idea
python:pycharm

下载安装
python:
下载地址:https://www.python.org/downloads/

配置环境变量
注释
python:
注释单行:#
注释多行(引号):''' ''';""" """

打印hello world
java:
public class HelloWorld
public static void main(String[] args){
Systemctl.out.println("Hello World!");
}

python:
print("Hello World!")

赋值变量
变量:
字母,数组,下划线组成的任意字符;
第一个字符不能是数字
其他可以使用的特殊含义字符
不能使拼音
只能是英文
常量:大写
例:
gf_of_oldboy
GFOfOldboy
java:
public class TestVeriable{
public static void main(String[] args){
int i1 = 12;
short s1 = 2;
int i2 = i1 + s1;
System.out.println(i2);
long long1 = 1234567890L;
System.out.println(long1);
char char1 = 'a';
char char2 = 'b';
char char3 = 'c';
System.out.println(char1 + char3);
char char4 = '\n';
System.out.println(char4);
System.out.println("123" + char4 + "456");
boolean b1 = true;
if(b1){
System.out.println("zeng 是个帅哥");
}
else{
System.out.println(char1);
}

}
}


python(不需要指定字符串,默认是string):
name = “rainbow”
age = 23
print(name,age)
print(type(age),type(name))


字符类型:
java:
1>数值型
整数类型:
byte:字节 1字节=8bit
short:
int:默认类型
long: 定义格式: long l1 = 123456L; 值的末尾加“L”或“l”;不加默认为int型;
浮点型:
float:单精度,4字节,值的末尾加“F”
double:双精度;8字节 默认类型
2>字符型
char:只能表示一个字符 "a"; (英文,中文,标点,转义字符\t \n);代表两个字节;引用时需要用“”号引起来。每个char都可以表示一个Unicon的值;
String:字符串 "ab"
3>布尔类型:boolean true或false,不能取null

python:
整形:python2**64次方会自动转换为long;python3只有int,没有long。
布尔值:真或假,1 或 0,Ture或False
bytes:二进制文件
str,bytes互相转换:str-->bytes:encode bytes-->str:decode
例子
msg = ("你好中国")
print(msg)
print(msg.encode("utf-8"))
print(b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\xad\xe5\x9b\xbd'.decode("utf-8"))

字符串操作:
http://www.cnblogs.com/alex3714/articles/5717620.html
name = ("my name is {},i am {} years old")
print('a'.isdigit())
print(name.format("rainbow",23))

name = ("my name is {1},i am {0} years old")
print(name.format("rainbow",22))

name = ("my name is {name},i am {age} years old")
print(name.format(name="rainbow",age=23))

print('rainbowrainbow'.count('o')) #统计o在字符串出现的次数

print('rainbowrainbow'.capitalize()) #首字母大写
print('rainbowRAINBOW'.casefold()) #大写全部变小写
print('RAINBOW rainbow'.lower()) #大写变小写,同casefold
print('rainbow'.swapcase()) #大小写互换

print('rainbowRAINBOW'.center(50,'-')) #------------------rainbowRAINBOW------------------

print('123qw'.isnumeric())
print('你好中国'.encode("utf-8")) #b'# \xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\xad\xe5\x9b\xbd';encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
print(b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\xad\xe5\x9b\xbd'.decode())

print("rainbow".encode())
print(b'rainbow'.decode())

print('rainbow'.endswith('w')) #判断最后一个字符
print('rainbow'.endswith('r'))
print('rainbow\trainbow'.expandtabs(20)) #扩大tab为20个空格

print('rainbow'.find('a')) #找下标位置
print('my name is {name},my age is {age}'.format_map({'name':'rainbow','age':22})) #my name is rainbow,my age is 22

print('123'.isnumeric()) #同isdigit
print('123'.index('1')) #打印下标
print('123'.isalnum())
print('rainbow'.isalpha())
print('1A'.isdecimal()) #十进制
msg = ("rainbow","alex")
print("|".join(['alex', 'jack', 'rain'])) #alex|jack|rain
print('rainbow'.ljust(20,'-')) #rainbow-------------
print('rainbow'.rjust(20,'-')) #-------------rainbow
print('RAINBOW rainbow'.lower()) #大写变小写,同casefold
print(' \nrainbow'.lstrip()) #去掉左边的空格和回车
print('rainbow \n'.rstrip()) #去掉左边的空格和回车
print('----')

p = str.maketrans('acbdef','123456')
print('rainbow rainbow'.translate(p)) #互换

msg = "my name is {}, and age is {}"
print(msg.partition('is'))

print('rainbow'.replace('r','R')) #替换
print('rainbow rainbow'.replace('r','R',1))

print('book diary flower'.rsplit()) #['book', 'diary', 'flower']

 


强制转换字符类型:
java:
自动类型转换:
当容量小的数据类型和容量大的数据类型做运算时,容量小的会自动转化为容量大的数据类型.
char,byte,short ==> int ==> long ==> float ==> double
char,byte,short之间做运算 ==> int
char c1 = 'a'; //a为97
int i2 = 1;
int ii1 = i2 + c1;
System.out.println(ii1);

强制类型转换:"(类型)"
:容量大的转换为容量小的
long m1 = 123L;
int n1 = (int)m1;
常用字符串运算:只能是拼接运算
问题:
String st1 = “hello”
int myInt1 =12;
char ch1 = ‘a’;
Systemc.out.println(str1 + myInt1 + ch1);hello1297
Systemc.out.println(myInt1 + ch1 + str1);109hello
Systemc.out.println(ch1 + myInt1 +myINt1);204

python:
name = input("name:")
age= int(input("age:"))
print(type(age),type(str(age)))
job = input("job")
salary = input("salary")
infor = '''
__information__%s
Name:%s
Age: %d
Job:%s
salary: %s
'''%(name,name,age,job,salary)
print(infor)


从键盘输入(交互)
java:
导import包
java包链接参考:https://docs.oracle.com/javase/6/docs/api/
//1.导包

import java.util.Scanner;
class TestScanner{
public static void main(String[] main){
Scanner s = new Scanner(System.in); //2.创建一个Scanner类的对象
System.out.println("please systemout:"); //3.调用此对象的相关的方法,完成键盘输入的值的获取
String str = s.next(); //next():表示从键盘获取一个字符串
System.out.println(str);
}
}

python:
方法1:
username = input("username:")
password = input("password:")
print(username,password)

方法2:
name = input("name:")
age= input("age:")
job = input("job")
infor = '''
__information__%s
Name:%s
Age: %s
Job:%s
'''%(name,name,age,job)
print(infor)


name = input("name:")
age= input("age:")
job = input("job")
infor02 = '''
__information02__{0}
Name:{1}
Age: {2}
Job:{3}
salary: {4}
'''.format(name,name,age,job,salary)
print(infor02)

字符串拼接(%s引用):
user=input("user:")
age=input("age:")
salary=input("salary:")
job=input("job:")

'''方法1'''
info01 = '''
----------info01 is : %s---------------
user:%s
age:%s
salary:%s
job:%s
'''%(user,user,age,salary,job)

print(info01)

'''打印数据类型'''
print(type(age))

'''方法2'''
info02 = '''
----------info02 is : {0}---------------
user:{0}
age:{1}
salary:{2}
job:{3}
'''.format(user,user,age,salary,job)
print(info02)

数据类型转换:
age=int(age)
密文:
python:
import getpass
username = input("username:")
password = getpass.getpass("password:")
print(username,password)


流程控制:
if
java:
格式:
①if(条件表达式){ }

②if(条件表达式){
//执行的语句1;
}else{
//执行的语句2;
}

③if(条件表达式1){
//执行的语句1;
}else if(条件表达式2){
//执行的语句2;
}else if( 条件表达式3){
//执行的语句3;
}...
}else{
//执行的语句;
}

例1:
public class If{
public static void main(String[] args){
int i1 = 10;
int i2 = 20;

if(i1 == i2){
System.out.println("yes!");
} else{
System.out.println("no is not!");
}
}
}

例2:
import java.util.Scanner;
class IfTest{
public static void main(String[] args){

Scanner s = new Scanner(System.in);

System.out.println("Please enter the score of Xiao Ming:");
int score = s.nextInt();

if(score == 100){
System.out.println("prize a new car");
}else if(score > 80 && score <= 99){
System.out.println("prize a iphone");
}else if(score > 60 && score <= 80 ){
System.out.println("prize a book of practice");
}else{
System.out.println("it's nothing to get");
}
}
}

 

python:(*python必须缩进)
例1
username = ("rainbow")
password = ("abc123")

_username = input("username:")
_password = input("password:")

if username == _username and password == _password :
print("yes!")
else :
print("no is not!")


例2:猜年龄
age = 56
guess_age = int(input("guess_age:"))
if guess_age == age :
print("yes,you get it!")
elif guess_age > age:
print("think smaller")
else :
print("think bigger!")


无限循环
例1:无限循环加1
java:
格式:
for(;;){}
while(true){}

public class While {
public static void main(String[] args) {
int count = 0;
while (true){
count +=1;
System.out.println(count);
}
}
}

python:(严格缩进)
count = 0
while True:
count += 1
print("the count is:",count)


while if:
格式:
while if(java)
while(true){
...
if( ){
break;
}
...
}

例子:一直猜年龄
import java.util.Scanner;
public class WhileIf {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int age = 56;
while(true) {
System.out.println("请输入你猜的年龄:");
int guess_age = s.nextInt();
if(guess_age == age){
System.out.println("yes,you get it!");
}else if(guess_age > age){
System.out.println("think smaller");
}else {
System.out.println("think bigger");
}
}
}
}

优化,输入三次退出
import java.util.Scanner;
public class WhileIfThree {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int age = 56;
int i = 0;
while(i<3) {
System.out.println("请输入你猜的年龄:");
int guess_age = s.nextInt();
if(guess_age == age){
System.out.println("yes,you get it!");
break;
}else if(guess_age > age){
System.out.println("think smaller");
}else {
System.out.println("think bigger");
}
i++;
}
System.out.println("输入太多次了!");
}
}

 

while if (python):
例1:
age = 56
while True:
guess_age = int(input("guess_age:"))
if guess_age == age:
print("yes, you get it!")
break
elif guess_age > age:
print("think smaller")
else:
print("think bigger")

优化猜三次退出:
例2:
age = 56
count = 0
while count < 3:
guess_age = int(input("guess_age:"))
if guess_age == age:
print("yes, you get it!")
break
elif guess_age > age:
print("think smaller")
else:
print("think bigger")
count +=1
else:
print("you have tired too many times,fuck off")


例3:
询问是否继续猜:
age = 56
count = 0
while count < 3:
guess_age = int(input("guess_age:"))
if guess_age == age:
print("yes, you get it!")
break
elif guess_age > age:
print("think smaller")
else:
print("think bigger")
count +=1
if count == 3:
continue_comfirm = input("do you want continue:")
if continue_comfirm != 'n' :
count = 0

for循环:
循环打印1-10的数字:
java:
public class For {
public static void main(String[] args) {
for(int i = 0;i <10;i++) {
System.out.println("the number is :" + i);
}
}
}


python:
for i in range(10):
print("the number is :",i)

打印偶数:
for i in range(0,10,2):
print("the number is ",i)


break && continue
break:
>使用switch-case结构或者循环结构中
>在循环结构中,一旦执行到break,就跳出当前循环。

continue:使用在循环结构中
>一旦执行到continue,就跳出当次循环。

java
for(int i = 1;i <= 10;i++){
if(i % 4 == 0){
//break; //123
continue; //123567910
}
System.out.print(i);
}


python:
for i in range(10):
if i <5:
print("the number is :",i)
else:
continue #01234


模块
python
sys模块
'''
import sys
print(sys.path) #打印环境变量
print(sys.argv) #打印当前文件所在目录
print(sys.argv[4]) #带参数打印,打印第n# 个参数
'''

os模块
'''
import os
cmd = os.system("dir") #打印当前目录
print(cmd) #打印结果0为执行成功
'''


自己写模块调用:
login.py(模块)
import getpass
username = "rainbow"
password = "abc123"
guess_username = input("please enter the username :")
guess_password = input("please enter te password:")
if guess_username == username and guess_password == password:
print("yes , you get it !")
else:
print("wrong username or password!")


sys_mod.py(必须同目录调用,或者把模块放到第三方库存放路径下(通过sys模块获得路径))
import login


列表,数组
java:数组
python:列表
http://www.cnblogs.com/alex3714/articles/5717620.html
import copy
#列表增删改查找统计
names = ["Zhangsan","Lisi","Wangwu",["Yuliu","Liuneng"],"Chenqi","Wangwu"]
#浅copy
names2 = names.copy()
print(names)
print(names2)
names[0] = ("Hello") #names2未修改
print(names)
print(names2)
names[3][1] = ("LIUNENG") #names2修改了
print(names)
print(names2)
#深copy,调用copy模块
names2 = copy.deepcopy(names)
print("--",names)
print("--",names2)
#循环
#range(0,10,2)
print(names[0:-1:2]) #range(0,10,2)

for i in names:
print(i)

#print(names[-1]) #切片
#print(names[-3:]) #切片
#print(names[0:3]) #切片0和-1可以省略
#增
#names.insert(1,"Nihao")
#names.append("Hello")
#print(names)
#删1
#del names[0] == names.pop(0)
#names.pop()
#names.remove("Wangwu")
#print(names)
#names.clear()
#改
#names[0] = "Liuba"
#反转reverse
#names.reverse()
#找
#print(names.index("Lisi"))
#print(names[(names.index("Lisi"))]) 找下标
#统计count
#names.append("Liujiu")
#names.insert(1,"Liujiu")
#print(names.count("Liujiu"))
#排序sort
#names.sort()
#print(names)
#扩展,合并extend
#names2 = (1,2,3,4,5)
#names.extend(names2)
#del names2
#print(names,names2)


*打印下标:
product_list = [1,2,3,4]
方法一:print(produce_list.index(item),item)
方法二:for i in enumerate(product_list):print(i) :打印下标
>>> a = [1,2,3]
>>> print(a)
[1, 2, 3]
>>> for i in enumerate(a):print(i)
元组(只读列表,不可修改)
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
names = ("alex","jack","eric")
它只有2个方法,一个是count,一个是index,完毕。

列表练习:购物车程序
需求:
1.启动程序后,让用户输入工资,然后打印商品列表
2.允许用户根据商品编号购买商品
3.用户选择商品后,检测余额是否够,够就直接扣款,不过就提醒
4.可随时退出,退出时,打印已购买商品和余额
product_list = [
('Iphone',5000),
('Watch',10000),
('T-shirt',300),
('Bike python',80),
('Drink',6)
]
shopping_list = []
salary = input("please enter the salary :")
if salary.isdigit():
salary = int(salary)
while True:
for index,item in enumerate(product_list):
print(index,item)
user_choice = input("你想买什么<<<")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice > -1:
price = product_list[user_choice]
if price[1] < salary:
shopping_list.append(price[0])
salary -= price[1]
print("your shopping cart is %s , your balance is \033[31;1m%s\033[0m" % (shopping_list, salary))
else:
print("\033[41;1m你的余额只剩%s,买个毛线啊\033[0m"%(salary))
print("your shopping cart is %s,your balance is %s"%(shopping_list,salary))
else:
print("\033[42;1myour product code %s is not exist! please try again\033[0m"%user_choice)
elif user_choice == 'q':
print("--------your shopping cart is : ---------")
for p in shopping_list:
print(p)
exit("\033[42;1myour balance is : %s\033[0m"%salary)
else:
print("Invalid salary")


优化:
product_list = [
("Starbuck",33),
("Book python",80),
("Iphone",10000),
("drink",8),
("car",60000),
("toy",200),
]
shopping_list = []
count = 0
while count <3:
salary = input("请输入你的工资:")
if salary.isdigit():
salary = int(salary)
while True:
for index,item in enumerate(product_list):
print(index,item)
user_choice = input("请输入你想买的产品编号:")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice > -1:
p_item = product_list[user_choice]
if salary > p_item[1]:
shopping_list.append(p_item[0])
salary -=p_item[1]
print("你的购物车里面有: %s ,你的薪水还有:\033[31;1m%s\033[0m "%(shopping_list,salary))
else:
print("\033[31;1m你的余额不足,还买个毛线啊!\033[0m")
print("\033[42;1m你的购物车现在有:%s,你的薪水还剩下:%s\033[0m"%(shopping_list,salary))
else:
print("\033[31;1m你输入的编号不存在,请重新输入!\033[0m ")
elif user_choice == 'q':
print("\033[31;1m--你最后购买的商品有--\033[0m")
for list in shopping_list:
print(list)
print("\033[31;1m你的薪水最后还剩下:%s\033[0m"%salary)
exit()
else:
print("\033[31;1m你输入的产品编号错误,请重新输入\033[0m")
else:
print("\033[31;1m你输入的工资不正确,请重新输入\033[0m")
count +=1
else:
print("你输入错误薪水次数过多,将退出程序!")

 

python-字典
特征:
key-value
dict是无序的,有key不需要下标
key必须是唯一的,so天生无法去重
代码:
dictionary = {
'stau01':"Rainbow",
'stau02':"Lisa",
'stau03':"Sir",
'stau01':"Tony"
}
#查
print(dictionary)
print(dictionary['stau01']) #一般使用这个
print(dictionary.get('stau01'))
'stau01' in dictionary
#改
dictionary['stau01'] = 'LiuSi'
print(dictionary)

dictionary['stau04'] = "LiuNeng"
print(dictionary)
#删
del dictionary['stau01']
print(dictionary)
dictionary.pop('stau04')
print(dictionary)

 

#多级字典
av_catalog = {
"欧美":{
"www.youporn.com": ["很多免费的,世界最大的","质量一般"],
"www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
"letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
"x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
},
"日韩":{
"tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
},
"大陆":{
"1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
}
}

av_catalog["大陆"]["1024"][1] += ",可以在做镜像就解决"
print(av_catalog["大陆"]["1024"])
#values
print(dictionary.values())
#keys
print(dictionary.keys())
#setdefault 如果没有就添加,如果有显示其值
dictionary.setdefault("stau02","Liuneng")
print(dictionary)
dictionary.setdefault("stau04","Liuneng")
print(dictionary)
#update 更新并添加
b = {
"stau02":"Caixikun",
5:2,
6:3
}
dictionary.update(b)
print(dictionary)

#items
print(dictionary.items()) #dict_items([('stau02','Caixikun'), ('stau03','Sir'), ('stau04','Liuneng'), (2,2), (3,3)])

#fromkeys
c = dict.fromkeys([1,2,3],"test01")
print(c)
#循环字典
for i in dictionary: #一般用这个
print(i,dictionary[i])

for j,k in dictionary.items(): #转换成列表,效率差
print(j,k)


*高亮显示:
字体高亮:\033[31;1mXXX\033[0m
背景颜色高亮:\033[41;1mXXX\033[0m

*退出程序:exit()

流程图工具:Visio
字符串操作:
lstrip 去左边的空格和换行
rstrip 去右边的空格和换行
python-集合set
http://www.cnblogs.com/alex3714/articles/5717620.html
特征:
去重
无序
关系测试
增删改查
list_1 = set([1,2,3,5,6])
list_2 = set([5,6,7,8])
print(type(list_1),type(list_2))
#交集
print(list_1.intersection(list_2))
print(list_1 & list_2)
#并集
print(list_1.union(list_2))
print(list_1 | list_2)
#差集
print(list_1.difference(list_2))
print(list_1 - list_2)
#对称差集 并集并去重
print("^".center(50,'-'))
print(list_1.symmetric_difference(list_2))
print(list_1 ^ list_2)
#父集
print("issuperset".center(50,"-"))
list_3=set([1,2,3])
print(list_1.issuperset(list_3))
print(list_1 >= list_3)
#子集
print("issubset".center(50,"-"))
print(list_3.issubset(list_1))
print(list_3 <= list_1)
print(list_3 in list_1)
#增
list_1.add(7)
list_1.add("hello")
list_1.update("hi")
print(list_1)
#删
list_1.remove("hello")
print(list_1)
#测量长度
print("len".center(50,'-'))
print(len(list_1))
#copy
print("copy".center(50,'-'))
s = set([1,2,3])
h = set("hello")
h = s.copy()
print(h)


python-文件读取
对文件操作流程
打开文件,得到文件句柄并赋值给一个变量
通过句柄对文件进行操作
关闭文件
#文件打印,写入
#方法1
'''
f = open("yesterday2",'w',encoding="utf-8")
f.write("相映成辉 \n") #如果没有yesterday文件,就创建
f.write("念念不忘 \n花丛懒顾")
#print("---next---"))
#data = f.read() #没有打印,因为文件句柄从头读到尾,尾部没有内容了,所以为空
f.close()
'''
#方法2(代替f.close()以免忘记关闭文件)
with open("yesterday2",'a',encoding="utf-8") as f:
f.write("%s end record \n"%time_current)
#文件循环打印,判断
f1 = open("yesterday",encoding='utf-8')
'''
for i in range(4):
print(f1.readline())
'''
'''
for i in f1.readlines():
print(i.strip())
'''
#不适合打开大文件(全部都先读到内存中,再打印)
'''
for index,i in enumerate(f1.readlines()):
if index == 1:
print("-----")
continue
print(index, i.strip())

#高效,(读一行到内存中显示一行,再删掉内存数据)
count = 0
for i in f1:
if count == 1:
print("-----")
count += 1
continue
print(i.strip())
count += 1
f1.close()
'''
#wb写二进制
'''
f2 = open("yesterday2",'wb')
print(f2.tell())
f2.write("please give me the kindness! \n".encode())
f2.seek(2) #移动光标的位置
print(f2.tell()) #显示光标所在位置
f1.close()
'''
#
f3 = open("yesterday2",'r+',encoding="utf-8")
f3.write("please give me the kindness! \n")
f3.write("yesterday once more \n")
f3.flush() #刷新让配置立即生效
f3.close()
#打印进度条
import sys,time
for i in range(30):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)

截断 f.read(10)
移动光标 seek tell
encoding flush刷新立即生效
读写r+ 写读w+ a+ wb (写只能从最后一行写)
socket3.0 网络传输只能用二进制传输

练习:修改文件替代sed
old = input("please enter the old words:")
new = input("please enter the new words:")
f = open("yesterday",encoding="utf-8")
f2 = open("yesterday2","r+",encoding="utf-8")

for i in f:
if old in i:
i = i.replace(old,new)
f2.write(i)
f.close()
f2.close()


python-excel读取
1.什么是xlrd模块?
  python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。

python-字符编码转换
python2
utf-8-unicode-gbk(把终端设备改成gbk查看)
gbk-unicode-utf-8(把终端设备编码改成utf-8查看)

#-*- coding:utf-8 -*-
#import sys
#print(sys.getdefaultencoding())

s = "你好"
s_to_unicode = s.decode("utf-8")
print(s_to_unicode,type(s_to_unicode))
s_to_gbk = s_to_unicode.encode("gbk")
print(s_to_gbk)

s_to_unicode = s_to_gbk.decode("gbk")
s_to_utf8 = s_to_unicode.encode("utf-8")
print(s_to_utf8)


python3
#-*- coding:gb2312 -*-
import sys
print(sys.getdefaultencoding())

h = "星期"
gb2312_to_utf8 = h.encode("utf-8") #本身就是unicode,所以无需decode
print(gb2312_to_utf8)

utf8_to_gb2312 = gb2312_to_utf8.decode("utf-8").encode("gb2312")
print(utf8_to_gb2312)

gb2312_to_utf82 = utf8_to_gb2312.decode("gb2312").encode("utf-8")
print(gb2312_to_utf82)

'''
#-*- coding:gbk -*-
import sys
print(sys.getdefaultencoding())

s = "你好"
utf8_to_gbk = s.encode("utf-8")
print(utf8_to_gbk)

gbk_to_unicode = utf8_to_gbk.decode("gbk")
gbk_to_utf8 = gbk_to_unicode.encode("utf-8")
print("utf8:",gbk_to_utf8)

utf8_to_unicode = gbk_to_utf8.decode("utf-8")
utf8_to_gbk2 = utf8_to_unicode.encode("gbk")
print("gbk2:",utf8_to_gbk2)
'''

函数
https://www.cnblogs.com/alex3714/articles/5740985.html
def hello():
print("helloworld")

hello()

编程方法:
面向对象:华山派-->类-->class
面向过程:少林派-->过程-->def 过程是没有返回值的函数
函数式编程:逍遥派-->函数-->def
优点:
代码复用
保持一致性
可扩展

def
"""****"""
x++
return 0


局部变量:这个函数就是变量的作用域,局部不可以改全局的字符串,整数类变量(但是字典,列表等可以改)
全局变量:适用于全局,在函数内修改不生效
在函数内修改全局变量:global
递归
函数嵌套自身函数
特征:
1.明确的结束条件
2.问题规模每递归一次都会比上一次的问题规模有所减少
3.效率低

函数式编程
指数学里的函数
lisp,hashshell,erlang
最火的编程方法:面向对象
高阶函数
>>> abs(-10)
10
函数的参数
1.return
返回值数=0 -->0
返回值数=1 -->object
返回值数>1 -->tuple
2.位置参数(形参,实参)
关键字参数(与形参顺序无关,关键参数必须放在位置参数之后)
默认参数
参数组
*arges :接收位置参数转换成元祖
**kwargs:把关键字参数转换成字典
结合使用
3.显示时间:
import time
time_format = '%Y-%m-%d %X'
time_current = time.strftime(time_format)
局部变量,全局变量
python-装饰器
第06章节:装饰器
装饰器本身是函数,装饰其他函数,就是为其他函数添加附加功能
原则:
1.不能修改函数源代码
2.不能修改被装饰函数的调用方式
知识点:
1.函数即变量 只要在调用之前定义了变量即可以调用; 变量即门牌号-->对应内存地址
2.高阶函数
a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
b:返回值中包含函数名(不修改函数的调用方式)
3.嵌套函数
高阶函数+嵌套函数=>装饰器
门牌号(内存地址)-->值
python内存回收机制:当变量没了就回收

#------高阶函数-----
''' 2.高阶函数
a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
b:返回值中包含函数名(不修改函数的调用方式)
'''
#-----1.函数即变量----
# x=1
# y=x
# func=bar
# func()
#---a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)---
import time
def bar():
time.sleep(3)
print("in the bar!")
def test(fun):
start_time = time.time()
print(fun)
fun()
stop_time = time.time()
print("the total time is :%s"%(stop_time-start_time))
test(bar)


#----b:返回值中包含函数名(不修改函数的调用方式)----
import time
def bar():
time.sleep(3)
print("in the bar!")
def test1(fun): bar=fun的内存地址
print(fun)
return fun
bar=test1(bar) #打印test1返回值, bar覆盖之前定义的函数
bar()


#-------嵌套函数-----
# def foo():
# def bar():
# print("in the bar!")
# bar()
# foo()
def foo():
x=1
def ma():
x=2
def son():
x=3
print(x)
son()
ma()
foo() #结果为3,只能从里往外

#------装饰器------
#装饰器:高阶函数+嵌套函数
#需要写一个装饰器:计算函数的执行时间
import time
def timer(fun): #timer(test1) fun=test1 <function timer.<locals>.deco at 0x000001AD3208EA60>
def deco(*args,**kwargs): #返回的是运行结果deco的内存地址
start_time=time.time()
fun(*args,**kwargs) #test1 把参数传进来
stop_time=time.time()
print("fun run time is :%s"%(stop_time-start_time))
return deco
@timer #同test1=timer(test1)
def test1():
time.sleep(3)
print("in the test1!")
@timer #同test2=timer(test2) =deco test2(name)=deco(name)
def test2(name):
time.sleep(3)
print("in the test2!",name)
test1() #--->deco
test2('alex')


装饰器高潮版练习:
__author__ = "Alex Li"
import time
user,passwd = 'alex','abc123'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。。")

return wrapper
return outer_wrapper

def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"

@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")

index()
print(home()) #wrapper()
bbs()

 

posted on 2019-05-31 14:02  rainbowdiary  阅读(131)  评论(0)    收藏  举报