Day01
Python的分类
Cpython:代码àc字节码->机器码 一行一行的编译执行
Pypy: 代码àc字节码->机器码 全部转换完再执行
其他python 代码-->其他字节码-->机器码
Python的执行
Windows:C:\Python35\python.exe D:\1.txt(python可执行文件路径---解释器 执行文件)
Linux:可以在文件的头部写#!/usr/bin/python python安装路径(用命令whereis python可以查到 )
Ps:文件格式用.py(潜规则)
编码
编码 |
字母占位 |
中文占位 |
特殊 |
|
Unicode |
万国码 |
2字节、16位 |
3字节、24位 |
占存储空间较大 |
Utf-8 |
对万国码的压缩 |
1字节、8位 |
3字节、24位 |
压缩了存储空间 |
Jbk、gb2312 |
中文的编码 |
1字节、8位 |
2字节、16位 |
不支持其他语言 |
Python编码
在Linux下文件头写# -*- coding:utf-8 -*- 表示解释器用utf-8编码解析,而文件本身存储编码不影响。
Ps:python2.7以前版本默认解释器编码为ascii ,3.0以后是utf-8
变量
命名要求
字母、数字、下划线组成,数字不能开头,不能是关键字
Ps:Python用_来分割,不使用驼峰式命名
输入、输出
Name=intput(“请输入用户名”) #name接收用户输入
Import getpass
Password=getpass.getpass(“请输入密码”)
条件判断if
if
if 条件:
成功走这里elif
elif条件:
符合条件走这里
else:
否则到这里
循环 while
while 条件:
continue # 立即开始下次循环
break # 跳出所有循环
循环for
练习:
1、使用while循环输入 1 2 3 4 5 6 8 9 10
i=0
while i<10 :
i
+= 1
if i==7:
continue
else:
print(i)
2、求1-100的所有数的和
sum = 0 i = 1 while i < 101 : sum += i i += 1 print(sum)
3、输出 1-100 内的所有奇数
i = 0 while i < 101: if i%2!=0: print(i) i += 1
4、输出 1-100 内的所有偶数
i = 0 while i<101: if i%2 == 0 : print(i) i += 1
5、求1-2+3-4+5 ... 99的所有数的和
sum = 0 i = 0 while i<100 : if i%2==0: sum -= i else : sum += i i += 1 print(sum)
6、用户登陆(三次机会重试)
name = "zhengsiyu" password = "537131" i = 3 while i>0 : name1 = input("name:") password1 = input("password:") if name1==name: if password1==password: print("login success!") i = 3 break else : print("password is wrong!please try it again!") i -= 1 else : print("name is not exist!") i -= 1 if i == 0 : print("you 3 times is used,byebye!")
***逻辑运算符(复习必看)
if 1 == 1 or 1 > 2 and 1 == 4:
print(‘正确‘)
else:
print(‘错误‘)
字符串
字符串定义
Name=“zhengsiyu”
Print(Name[1]) ===》 h
这里name就是一个字符串相当于str()
转换
字符串只有内容是数字才可以转换成int()
字符串拼接
name = "zhengsiyu" age = "29" message = name + age print(message)=======》zhengsiyu29
字符串格式化(%s占位)
name = "my name is %s,%d years old" name1 = input("name:") age1=int(input("age:")) name_str=name %(name1,age1) print(name_str)
运行结果是:(输入name:aa,年龄为11)
my name is aa,11 years old
判断子序列是否在字符串中(in)
name ="zhengsiyu" if ‘a‘ in name : print("yes") else: print("no")
ps:中文也可以识别
移除空白
name = " aaaa " #name = name.strip()左右两边空白都移除 #name = name.lstrip()移除左面空白 name = name.rstrip()移除右面空白 print(name)
分割
name ="zhengsiyu" first_name=name.split(‘s‘) print(first_name)
运行结果是:[‘zheng‘, ‘iyu‘]
如果分割符不存在则不进行分割
first_name=name.split(‘l‘)
运行结果是:[‘zhengsiyu‘]
name ="zhengsiyuzhengsiyuzhengsiyu" first_name=name.split(‘u‘,2) print(first_name)
运行结果是:[‘zhengsiy‘, ‘zhengsiy‘, ‘zhengsiyu‘]
name ="zhengsiyuzhengsiyuzhengsiyu" first_name=name.split(‘u‘,3) print(first_name)
运行结果是:[‘zhengsiy‘, ‘zhengsiy‘, ‘zhengsiy‘, ‘‘]
name ="zhengsiyuzhengsiyuzhengsiyu" first_name=name.split(‘u‘,6) print(first_name)
运行结果是:[‘zhengsiy‘, ‘zhengsiy‘, ‘zhengsiy‘, ‘‘]
长度
name ="zhengsiyuzhengsiyuzhengsiyu" first_name=name.split(‘u‘,6) print(first_name) print(len(first_name))
运行结果是:[‘zhengsiy‘, ‘zhengsiy‘, ‘zhengsiy‘, ‘‘]
4
Ps:分割完以后按模块计算长度
索引
就是下标
name ="zhengsiyuzhengsiyuzhengsiyu" print(name[2])
运行结果是:e
切片
str="12345567asdffg,sde102" print(str[1])# : 2 print(str[0:2])#从第一个一直到第二个: 12 print(str[0::4])#每隔四个取值一次:15afd2 print(str[5:9])#第五个到第九个:567a print(str[3:])#第三个到结尾:45567asdffg,sde102 print(str[2:-4])#第二个到倒数第四个:345567asdffg,sd print(str[-6:])#输出最后6个字符:sde102 print(str[:-6])#第一个到最后六个:12345567asdffg, print("------") print(str[-3:-1])#10 print(str[-1::-2])#21d,fda6531
列表
创建列表
a = [‘alex‘,‘狗‘,‘eric‘,123]
a=list(a = [‘alex‘,‘狗‘,‘eric‘,123])
判断列表中元素是否存在(in)
table = ["name","age","tom"] if ‘name‘ in table : print("yes") else : print("no")
程序运行结果:yes
索引/长度/切片(同字符串)
增list.append
table = ["name","age","tom"] table.append(‘hhhhh‘) print(table)
程序运行结果:[‘name‘, ‘age‘, ‘tom‘, ‘hhhhh‘]
增插入list.insert
table = ["name","age","tom"] table.insert(1,‘aaa‘) for item in table : print(item)
程序运行结果:
name
aaa
age
tom
ps:如果插入的下标越界则插到最后一位
table = ["name","age","tom"] table.insert(7,‘aaa‘) # for item in table : # print(item) print(table)
程序运行结果:[‘name‘, ‘age‘, ‘tom‘, ‘aaa‘]
删
1、通过元素内容删除
table = ["name","age","tom"] table.remove(‘age‘) print(table)
程序运行结果:[‘name‘, ‘tom‘]
Ps:如果删除不存在的元素,则会报错
2、通过索引删除
table = ["name","age","tom"] del table[1] print(table)
程序运行结果:[‘name‘, ‘tom‘]
Ps:如果删除下标越界,则会报错
改
通过索引修改
table = ["name","age","tom"] table[0]=‘nanan‘ print(table)
程序运行结果:[‘nanan‘, ‘age‘, ‘tom‘]
根据元素内容修改:
#将元素age修改为www n=0 table = ["name","age","tom"] if ‘age‘ in table : for i in table : n += 1 if i == ‘name‘ : print(n) break else : print("\‘age\‘ is not exist in table") table[n] = ‘www‘ for item in table : print(item)
字典(字典是无序的)
我理解的字典:
字典可以看做是一个对象的属性,列表就是好多个人的集合
定义
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111}
ps:可以定义为空v={}
索引获取值
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111} name=v[‘name‘] print(name)
程序运行结果:zzz
增加,无,增加;有,修改
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111} v[‘address‘]=‘sdfsdfsfsfsdfsf‘ print(v)
ps:字典是无序的,所以增加到什么位置不确定
程序运行结果:{‘address‘: ‘sdfsdfsfsfsdfsf‘, ‘name‘: ‘zzz‘, ‘age‘: ‘12‘, ‘id‘: 13020111}
删除
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111} v[‘address‘]=‘sdfsdfsfsfsdfsf‘ del v[‘age‘] print(v)
程序运行结果:{‘id‘: 13020111, ‘address‘: ‘sdfsdfsfsfsdfsf‘, ‘name‘: ‘zzz‘}
遍历(复习必看)
遍历字典
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111} v[‘address‘]=‘sdfsdfsfsfsdfsf‘ for key,val in v.items() : print (key,val)
程序运行结果:
address sdfsdfsfsfsdfsf
age 12
id 13020111
name zzz
遍历键值:
for i in v.keys() : print(i)
程序运行结果:
age
id
name
address
遍历值
for i in v.values() : print(i)
程序运行结果:
zzz
12
13020111
sdfsdfsfsfsdfsf
字典长度(len())
v = {‘name‘:‘zzz‘, ‘age‘:‘12‘, ‘id‘:13020111} v[‘address‘]=‘sdfsdfsfsfsdfsf‘ print(len(v))
程序运行结果:4
练习(复习必看)
用户登录系统,使用字典列表验证密码
table = [{‘username‘:‘jojo‘,‘password‘:‘123456‘},
{‘username‘:‘admin‘,‘password‘:‘537131‘},
{‘username‘:‘was‘,‘password‘:‘was‘},
{‘username‘: ‘wasqqq‘, ‘password‘: ‘wasqqq‘}]
i = 3
for item in table :
name = input("username:")
pwd = input("password:")
if name == item[‘username‘] and pwd == item[‘password‘]:
print("login success")
break
else :
i -=1
if
i == 0 :
print("login
fail,your times is out!")
break
print("username or password is wrong ,please try it
again!")
***读取文件内容(复习必看) # f1 = open(‘G:\\_python学习视频\\day01\\db.txt‘,‘r‘) f1 = open(‘db.txt‘,‘r‘)#同级目录不需要写路径 date = f1.read() f1.close() #print(date) usr_info_list = [] usr_str_list = date.split(‘\n‘) for item in usr_str_list : temp = item.split(‘|‘) v = {‘name‘:temp[0], ‘pwd‘:temp[1], ‘times‘:temp[2]} usr_info_list.append(v) print(usr_info_list)
***课上练习题,读出文件并验证用户命密码(三次机会)
把文件内容存入到字典以后,字典是用str类型存储,要使用需先转int在进行加减法,分两个步骤
元素分类
有如下值集合
v1 = [11,22,33,44,55,66,77,88,99,90],
将所有大于
66 的值保存至字典的第一个key中,将小于
66 的值保存至第二个key的值中。
即:
{‘k1‘: 大于66的所有值, ‘k2‘: 小于66的所有值}
v2 = {‘k1‘: [],‘k2‘:[] }
v = [11,22,33,44,55,66,77,88,99,90] v1 =[]#big v2 =[]#little k = {} for i in v : if i > 66 : v1.append(i) elif i< 66 : v2.append(i) else : v3 = i k[‘k1‘] = v1 k[‘k2‘] = v2 k[‘k‘]=v3 print(k)
代码输出结果:{‘k2‘: [11, 22, 33, 44, 55], ‘k1‘: [77, 88, 99, 90], ‘k‘: 66}
购物车
price = int(input("您有多少总资产?")) shopping_car = [] totle_price = 0 goods = [ {"name": "电脑", "price": 1999,"id":"001"}, {"name": "鼠标", "price": 10,"id":"002"}, {"name": "游艇", "price": 20,"id":"003"}, {"name": "美女", "price": 998,"id":"004"}, ] goods_list = [] for item in goods : goods_name = item[‘name‘] goods_id = item[‘id‘] goods_info = goods_id+"-"+goods_name goods_list.append(goods_info) state = False while True : if state : #打印购物清单 for item1 in shopping_car : print(item1[‘name‘]+str(item1[‘price‘])) str ="购物车总额:%d" str1 =str %(totle_price) print(str1) #结账 if_buy = input("结账请按任意键,退出请按0!") if if_buy != 0 : if price >= totle_price : print("购买成功!") else : print("余额不足,购买失败!") else: print("BYE-BYE!") break break else: print("请选择您要加入购物车的商品id") input_id = input(goods_list) for item in goods : if input_id == item[‘id‘] : # print(item[‘price‘]) shopping_car.append(item) totle_price += item[‘price‘] message1 ="您将\"%s\"添加进了购物车,现在购物车总额:%d" message = message1 %(item[‘name‘],totle_price) print(message) break else: print("您输入的商品不存在,请重新选择") go_on_shopping= input("继续购物请按-1,退出并查看购物车清单请按-2,清空购物车并退出请按其他键!") if go_on_shopping ==‘1‘ : continue elif go_on_shopping == ‘2‘ : state = True else : print("您的购物车已清空,BYE-BYE") break
用户交互,显示省市县三级联动的选择
我写这个程序的时候写了if判断,判断用户输入的内容和字典内容进行匹配,其实可以看做多维数组,把索引用用户变量代替
dic = { "河北": { "石家庄": ["鹿泉", "藁城", "元氏"], "邯郸": ["永年", "涉县", "磁县"], } "河南": { ... } "山西": { ... } } for v in dic.keys(): print(v) inp = input(‘>>>‘) dic[inp]
程序代码如下:
dic = { "河北": { "石家庄": ["鹿泉", "藁城", "元氏"], "邯郸": ["永年", "涉县", "磁县"], }, "河南": { "郑州":["小郑州1","小郑州2"], "西安":["小西安1","小西安2"] }, "山西": { "太原":["小太原1","小太原2"], "大同":["小大同1","小大同2"] } } for i in dic.keys(): print (i) proviece = input(">>>") for citys in dic[proviece].keys(): print(citys) city = input(">>>") for xian in dic[proviece][city]: print(xian)