模块
别人写好了的程序,可下载或直接调用,分为:
标准库(不用安装,直接可以用的 像getpass,sys,os)
第三方库(必须安装才可以用)
PS: python的标准库一般存在 lib (site-packages的上一层);的第三方库一般存在 site-packages
sys:
importsysprint(sys.path) #" . " : expand methods of XXXXXXX
print(sys.argv) #pycharm里是绝对路径,cmd里相对路径 (其实就是打印的相对路径,不会打印绝对路径)#为什么pychram是绝对路径? 因为调用的时候写的这个脚本名字的路径就是绝对路径,pycharm在自己调用的时候写的就是绝对路径
print(sys.argv[2]) #取第二个参数
os:
importos#可以从python中调用shell的命令#或者在系统中创建一个文件,目录#查看当前目录下有多少文件,查看文件的大小
cmd_res= os.system("dir")#只执行命令,只输出在屏幕上,不保存结果
cmd_res1= os.popen("dir")#打印的是一个内存的对象地址
cmd_res1 = os.popen("dir").read()#执行命令,然后结果存到了一个内存里临时的地方,必须用read方法去取
print("-->",cmd_res1) #0 means success
#在当前目录下,创建一个目录
os.mkdir("new_dir") #shows on the left
第三方库(login.py):
#文件和login在同一个目录下的时候
importlogin#文件和login不在同一个目录下,copy login.py到site-package下去
什么是PYC?
python程序运行时,编译的结果是保存在位于内存中的PyCodeObject中;
python程序运行结束时,python解释器将PyCodeObject写回到pyc文件中
python程序第二次运行的时候,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程
所以,pyc文件其实是PyCodeObject的一种持久化保存方法
Q:pyc保存了,但是源代码重新被改了怎么办?
A: python检测文件,再检测时间,然后看pyc的更新时间和源代码的更新时间哪个最新.
数据类型:
1.数字
int 整型(数)
long 长整型 python3没有这个
float 浮点数
浮点不是小数
浮点的表示形式是小数
小数不只包括浮点 forget it anyway
complex 复数
2.布尔值
真 or 假
1 or 0
3.字符串
"hello world”
4.列表
name = ['momo','shirley','curry']#or
name = list( ['momo','shirley','curry'])
5.元组
和列表差不多,但是不能修改,只能读
ages = (1,2,3,4)#or
ages = tuple((1,2,3,4))
6.字典
字典是无序的
person = {"name":{ "momo"}, "age": {"22"}}#or
person = dict({"name":{ "momo"}, "age": {"22"}})
数据运算:
算术运算:
// 取整数
9/2 输出结果4
9.0/2/0 输出结果4.0
% 取模 (返回除法的余数)
10%2 输出结果0 11%2 输出结果1
+
-
*
/
** 幂
比较运算:
== 等于
!= 不等于
<> 不等于
>
<
>=
<=
赋值运算:
= 简单的赋值运算符
+= 加法赋值运算符 c+=a c=c+a
-= 减法赋值运算符 c-=a c=c-a
*= 乘法赋值运算符
/= 除法赋值运算符
%= 取模赋值运算符
**= 幂赋值运算符
//= 取整除赋值运算符
逻辑运算:
and
or
not
成员运算:
in
not in
身份运算:
is
is not
位运算:(practice)
& 按位与运算符 a & b 12 = 0000 1100
| 按位或运算符 a | b 61 = 0011 1101
^ 按位异或运算符 a ^ b 49 = 0011 0001
~ 按取位反运算符 a ~ b - -61 = 1100 0011
<< 左移动运算符 a << 2 240 = 1111 0000
>> 右移动运算符 a >> 2 15 = 0000 1111
eg.
a = 60 #60 = 0011 1100
b = 13 #13 = 0000 1101
各种操作!!!怎么操作呢?
1.列表操作:
列表是有序的,可做增删减查,也可以多层嵌插列表、元组、字典任何东西
names = ["ZhangYang", "GuYun","XiangPeng","XuLiangChen"] #define a list
#list通过下标找元素
names[0] #正数第一个元素,下标从零开始往右走
name[-1] #倒数第一个元素
loop for a list
>>>for i innames:print(i)"ZhangYang"
"GuYun"
"XiangPeng"
"XuLiangChen"
View Code
切片
print(names[-1]) #unknown length, 取最后一个元素
print(names[0],names[2]) #取第一项和第三项
print(names[1:3]) #顾头不顾尾哈哈哈, 从1-2
print(names[0:3]) #从0-2 和 print(names[:3])
print(names[-2:]) #unknown length, 取最后两项
print(names[:]) #从头到尾
print(names[::2]) #从头到尾,间隔2
print(names[0:-1:2]) #从0到倒数第二,间隔2
View Code
添加
names.append("LeiHaiDong") #adding more names
View Code
插入
#插入准确的位置,但是不能同时插两个
names.insert(1,"ChenRongHua") #插在原本第一项的前面
names.insert(3,"XinZhiYu") #插在原本第三项的前面
View Code
修改
#修改替换
names[2] = "XieDi" #把第三项幻城xiedi
View Code
删除
names.remove("ChenRongHua")del names[1]
names.pop()#delete the last one if no index input
#del names[1] = names.pop(1)
View Code
统计
print(names.count("ChenRongHua")) #names counting from the list
View Code
排序和翻转
names.reverse() #reverse the list
names.sort() #sort in letters & if initials are numbers or notations, then notations-->umbers-->letters
View Code
找下标
names = ["ZhangYang", "GuYun","XiangPeng","XuLiangChen"]print(names.index("XieDi")) #但只能找到第一个xiedi的下标
View Code
copy!!!!来了!! IMPORTANT!
light copy:
names = ["4ZhangYang", "#!GuYun","xXiangPeng",["alex","jack"],"ChenRongHua","XuLiangChen"]
name2= names.copy() #浅copy,只copy第一层,所以name2 之后no change
print(names)print(name2)
names[2] = "向鹏" #name2 no change
names[3][0] = "ALEXANDER" #name2 changed 替换alex
print(names)print(name2)
View Code
names = ["4ZhangYang", "#!GuYun","xXiangPeng",["alex","jack"],"ChenRongHua","XuLiangChen"]
name2=namesprint(names)print(name2)
names[2] = "向鹏" #name2也变了(如果是简单字符串和数字是不会变的(见notes 1 小知识),但是列表里会跟着变)
names[3][0] = "ALEXANDER" #name2 changed
print(names)print(name2)
View Code
deep copy:
importcopy
names= ["4ZhangYang", "#!GuYun","xXiangPeng",["alex","jack"],"ChenRongHua","XuLiangChen"]
name2=copy.deepcopy(names)print(names)print(name2)
names[2] = "向鹏" #name2 no changes
names[3][0] = "ALEXANDER" #name2 no changes
print(names)print(name2)
View Code
2.元组操作
元组是有序的,但是只可读
统计和找下标
ages = (1,2,3,4) #define a tuple
print(ages.count("1")) #统计
print(ages.index(3)) #找下标
people= ("name","age","salary","occupation")print(people.count("name"))print(people.index("age"))
View Code
3.字符串操作
字符串是不可修改的
eg. 如果变大小写,原本的字符串就会被覆盖掉
11111111111111111
name = "my name is alex"name1= "my \tname is alex" #\t 空一隔
name2 = "my \tname is {name} and i am {year} old" #format
print(name.capitalize()) #首字母大写
print(name.title()) #每个单词第一个字母大写
print(name.zfill(50)) #在字符串前加50个0
print(name.count("a")) #统计a的数量
print(name.center(50,"-"))print(name.ljust(50,'*'))print(name.rjust(50,'-'))print(name.encode) #字符串转二进制
print(name.endswith("ex")) #判断"ex"结尾
print(name.find("name"))print(name[name.find("name"):9]) #字符串贴片
print(name1)print(name1.expandtabs(tabsize=30)) #30个空格
print(name2.format(name= 'alex',year=23))print(name2.format_map({'name':'alex','year':12}))
code1
输出:
My name isalex
My Name Is Alex
00000000000000000000000000000000000my nameisalex2
-----------------my name is alex------------------my nameis alex***********************************
-----------------------------------my name isalexTrue3name i
my nameisalex
my nameisalex
my nameis alex and i am 23old
my nameis alex and i am 12old1234
1,2,3,4
1+2+3+4aLex li7['a', 'ex', 'i', '']
['1', '2', '3', '4']
['1+2', '+3+4']
['1+2+3+4']
code1
22222222222222222
print('ab23!'.isalnum()) #判断是否是阿拉伯数字
print('Aab'.isalpha()) #判断是否纯英文字符
print('1A'.isdecimal()) #判断是否是十进制
print('ab23!'.isdigit()) #判断是否是整数
print('A1a'.isidentifier()) #判断是不是一个合法的标识符
print('ab23'.islower()) #判断是不是小写
print('aG'.isupper()) #判断是不是大写
print('33.33'.isnumeric()) #判断是不是只有数字 forget it
print('ab23!'.isspace()) #判断是不是空格
print('My Name Is'.istitle()) #判断是不是标题大写
print('ab23!'.isprintable())print('Alex'.lower()) #all lower
print('Alex'.upper()) #all upper
print('Alex Li'.swapcase())print('Alex\n'.strip()) #strip 会去掉两头的空格和回车
print('\nAlex'.lstrip()) #\n 换行
print('Alex\n'.rstrip())print('---')
code2
输出:
False
True
False
False
True
True
False
False
False
True
True
alex
ALEX
aLEX lI
Alex
Alex
Alex---
code2
33333333333333333
#join
print(''.join(['1','2','3','4']))print(','.join(['1','2','3','4']))print('+'.join(['1','2','3','4']))print('alex li'.replace('l','L',1))print('alex lil'.rfind('l')) #找到最后值的下标
print('al ex lil'.split('l')) #字符串 --> 列表
print('1+2+3+4'.split('+'))print('1+2\n+3+4'.splitlines())print('1+2+3+4'.split('\n'))
code3
输出:
1234
1,2,3,4
1+2+3+4aLex li7['a', 'ex', 'i', '']
['1', '2', '3', '4']
['1+2', '+3+4']
['1+2+3+4']
code3
随机密码:
#随机密码!!
p = str.maketrans("abcdef",'123456')print("alex li".translate(p)) #用上面abcde所赋的值(对应的数),去转化“alex li”
4.字典
字典一种key——value的数据类型
通过笔划,字母来查对
字典是无序的,没有下标 (也不需要下标,通过key去找);但是列表有下标,表示位置信息
字典可以多层嵌插字典、列表、元组任何东西
eg.1 loop
#key-value
info ={'stu1101': "TengLan Wu", #key --> stu1101; value --> name
'stu1102': "LongZe Luola",'stu1103': "XiaoZe Maliya",
}#basic loop
for i ininfo:print(i,info[i]) #print key and value
#loop 没有上面高效 不推介
for k,v ininfo.items():print(k,v)
eg.2 update and combine two dicts
#another dict
b ={'stu1101':"Alex",1:3,2:5}
info.update(b)#combine two dicts, keep different items and replace the same one
eg.3 create new dict
>>>c = info.fromkeys([6,7,8],[1,{"name":"alex"},444]) #create new dict
>>>print(c)
{6: [1, {'name': 'alex'}, 444], 7: [1, {'name': 'alex'}, 444], 8: [1, {'name': 'alex'}, 444]}>>>c[7][1]['name'] = "Jack Chen" #全改了,不是单独改了一份数据
>>>print(c)
{6: [1, {'name': 'Jack Chen'}, 444], 7: [1, {'name': 'Jack Chen'}, 444], 8: [1, {'name': 'Jack Chen'}, 444]}
eg.4 dict converts to list(item), find, existence, modify, add, delete
#dict converts to list
print(info.items())#find
print(info["stu1101"]) #if 100% sure it does exist
print(info.get('stu1104')) #if no such item exists, returns none
#judge weather XXX in the dict
print('stu1103' in info) #returns T or F
#modify
info["stu1101"] = "武藤兰"info["stu1104"] = "CangJingKong" #if no such item exists, then adding this item automatically
#del
del info["stu1101"] #or info.pop("stu1101")#del info delete the whole dict#info,popitem() free deleting
污污污污小例子:(多级字典嵌套及操作)
av_catalog ={"欧美":{"www.youporn.com": ["很多免费的,世界最大的","质量一般"],"www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],"letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],"x-art.com": ["质量很高,真的很高","全部收费,屌比请绕过"]
},"日韩":{"tokyo-hot":["质量怎么样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
},"大陆":{"1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
}
}
av_catalog["大陆"]["1024"][1] = "可以在国内做镜像" #改
print(av_catalog.values()) #打印value
print(av_catalog.keys()) #打印key
#setdefault 去字典里面找,如果有,就返回;如果没有,创建一个新的
av_catalog.setdefault("台湾",{"www.baidu.com":[1,2]})print(av_catalog)
av_catalog.setdefault("大陆",{"www.baidu.com":[1,2]}) #大陆不会有变化 BUT 也没有新创建一个值
print(av_catalog)
View Code
小程序之 购物车
product_list =[
('Iphone',5800),
('Mac Pro',9800),
('Bike',800),
('Watch',10600),
('Coffee',31),
('Alex Python',120),
]
shopping_list=[]
salary= input("Input your salary:") #工资只要输入一次,所以写在循环外面
if salary.isdigit(): #判断整数
salary =int(salary)whileTrue:for index,item in enumerate(product_list): #enumerate: 把列表下标直接取出来
print(index,item)
user_choice= input("选择要买嘛?>>>:")ifuser_choice.isdigit():
user_choice=int(user_choice)if user_choice < len(product_list) and user_choice >=0:
p_item= product_list[user_choice] #通过下标把商品取出来
if p_item[1] <= salary: #买得起
shopping_list.append(p_item)
salary-= p_item[1] #扣钱
print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m"%(p_item,salary)) #red31,green32
else:print("\033[41;1m你的余额只剩[%s]拉,还买个毛线\033[0m"% salary) #red_background41 green_background42
else:print("product code [%s] is not exist!"%user_choice)elif user_choice == 'q':print("------------- shopping list --------------")for p inshopping_list:print(p)print("Your current balance:",salary)
exit()else:print('invalid option')
View Code
小程序之 三级菜单
data ={'北京':{"昌平":{"沙河":["oldboy","test"],"天通苑":["链家地产","我爱我家"]
},"朝阳":{"望京":["奔驰","陌陌"],"国贸":["CICC","HP"],"东直门":["Advent","飞信"]
},"海淀":{},
},'山东':{"德州":{},"青岛":{},"济南":{},
},'广东':{"东莞":{},"常熟":{},"佛山":{},
},
}
exit_flag= False #为了在任意一层可以退出
while notexit_flag:for i indata:print(i)
choice= input("选择进入1>>:")if choice in data: #在不在字典里
while not exit_flag: #死循环
for i2 indata[choice]:print("\t",i2)
choice2= input("选择进入2>>:")if choice2 indata[choice]:while not exit_flag: #死循环
for i3 indata[choice][choice2]:print("\t\t",i3)
choice3= input("选择进入3>>:")if choice3 indata[choice][choice2]:for i4 indata[choice][choice2][choice3]:print("\t\t",i4)
choice4= input("最后一层,按b返回>>:")if choice4 == "b":pass #什么也不做,不写就报错了,其实就是个占位符
elif choice4 == "q":
exit_flag=Trueif choice3 == "b":break
elif choice3 == "q":
exit_flag=Trueif choice2 =="b":break
elif choice2 == "q":
exit_flag= True
View Code