Python Day2

 一、入门拾遗  

模块

Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,以后的课程中会深入讲解常用到的各种库,现在,我们先来象征性的学2个简单的。

sys

1 import sys
2 print(sys.path) #打印环境变量
3 print(sys.argv)
4 print(sys.argv[2]) #接受执行脚本时输入的第二个参数

os

1 import  os
2 cmd_res = os.system("dir")  #执行命令,不保存结果
3 cmd_res = os.popen("dir").read()
4 print("---->",cmd_res)
5 os.mkdir("new_dir")        #在当前路径下创建一个新的目录

完全结合一下

1 import os,sys
2  
3 os.system(''.join(sys.argv[1:])) #把用户的输入的参数当作一条命令交给os.system来执行

pyc是个什么鬼?

参考大王博客:http://www.cnblogs.com/alex3714/articles/5465198.html

PS:pyc 是预编译的字节码

 

数据类型

1、数字

2 是一个整数的例子。
长整数 不过是大一些的整数。
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子,其中-5,4为实数,j为虚数,数学中表示复数是什么?。

int(整型)             PS:python3没有长整型

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
float(浮点型)
      先扫盲 http://www.cnblogs.com/alex3714/articles/5895848.html 
  浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数)
  复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
注:Python中存在小数字池:-5 ~ 257
 
2、布尔值
  真或假
  1 或 0
3、字符串
1 name = 'Breakering'
4、列表
1 l = ["Breakering","Profhua","Wolf"]
5、元组(不可变列表)
1 t = ("Breakering","Profhua","Wolf")
6、字典(无序)
1 person_dict = {
2                      "Breakering":23,
3                      "Profhua":24
4 }

 

数据运算

算数运算:

比较运算:

赋值运算:

逻辑运算:

成员运算:

身份运算:

位运算:

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author:Breakering
 4 a = 80             #80  = 0101 0000
 5 b = 60             #60  = 0011 1100
 6 
 7 c = a & b          #16  = 0001 0000
 8 
 9 d = a | b          #124 = 0111 1100
10 
11 e = a ^ b          #108 = 0110 1100    #相同为0,不同为1
12 
13 f = ~a             #-81 = 1010 1111  175-256=-81
14 
15 g = a << 2         #320 = 1 0100 0000
16 
17 h = a >> 2         #20  = 0001 0100

*按位取反运算规则(按位取反再加1)   详解http://blog.csdn.net/wenxinwukui234/article/details/42119265

 

运算符优先级:

 

更多内容:http://www.runoob.com/python/python-operators.html

 

判断if....else

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author:Breakering
 4 age_of_oldboy = 56
 5 
 6 count = 0
 7 
 8 while count < 3:
 9     guessage = int(input("Guessage:"))
10     if age_of_oldboy == guessage:
11         print("Yeah you got it !")
12         break
13     elif age_of_oldboy > guessage:
14         print("Think bigger!")
15     else:
16         print("Think smaller!")
17     count += 1
18     if count == 3:
19         continue_confirm = input("Do you want to continue:[Y/N]")
20         if continue_confirm != "N":
21             count = 0

 

bytes类型

python3的bytes&str之别

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author:Breakering
 4 
 5 info = "我是最棒的"
 6 
 7 print(info)
 8 #我是最棒的
 9 print(info.encode(encoding="utf-8"))
10 #b'\xe6\x88\x91\xe6\x98\xaf\xe6\x9c\x80\xe6\xa3\x92\xe7\x9a\x84'
11 print(info.encode(encoding="utf-8").decode(encoding="utf-8"))
12 #我是最棒的

三元运算

1 result = 值1 if 条件 else 值2

如果条件为真:result = 值1
如果条件为假:result = 值2

进制

  • 二进制,01
  • 八进制,01234567
  • 十进制,0123456789
  • 十六进制,0123456789ABCDEF  二进制到16进制转换http://jingyan.baidu.com/album/47a29f24292608c0142399cb.html?picindex=1

计算机内存地址和为什么用16进制?

为什么用16进制
1、计算机硬件是0101二进制的,16进制刚好是2的倍数,更容易表达一个命令或者数据。十六进制更简短,因为换算的时候一位16进制数可以顶4位2进制数,也就是一个字节(8位进制可以用两个16进制表示)
2、最早规定ASCII字符集采用的就是8bit(后期扩展了,但是基础单位还是8bit),8bit用2个16进制直接就能表达出来,不管阅读还是存储都比其他进制要方便
3、计算机中CPU运算也是遵照ASCII字符集,以16、32、64的这样的方式在发展,因此数据交换的时候16进制也显得更好
4、为了统一规范,CPU、内存、硬盘我们看到都是采用的16进制计算


16进制用在哪里
1、网络编程,数据交换的时候需要对字节进行解析都是一个byte一个byte的处理,1个byte可以用0xFF两个16进制来表达。通过网络抓包,可以看到数据是通过16进制传输的。
2、数据存储,存储到硬件中是0101的方式,存储到系统中的表达方式都是byte方式

3、一些常用值的定义,比如:我们经常用到的html中color表达,就是用的16进制方式,4个16进制位可以表达好几百万的颜色信息。

二、本节内容  

列表

列表是我们以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author:Breakering
 4 names = ["Breakering","Profhua","Wolf","Dog","Diaosi","FlyDog"]                    #定义一个列表
 5 
 6 print(names[0])
 7 #Breakering
 8 print(names[1])
 9 #Profhua
10 print(names[2])
11 #Wolf
12 print(names[-1])
13 #FlyDog

切片

 1 #切片
 2 print(names[1:4])                              #取下标1至下标4之间的数字,包括1,不包括4
 3 #['Profhua', 'Wolf', 'Dog']
 4 print(names[1:-1])                             #取下标1至-1的值,不包括-1
 5 #['Profhua', 'Wolf', 'Dog', 'Diaosi']
 6 print(names[:3])                               #如果是从头开始取,0可以忽略
 7 #['Breakering', 'Profhua', 'Wolf']
 8 print(names[3:])                               #如果想取最后一个,必须不能写-1,只能这么写
 9 #['Dog', 'Diaosi', 'FlyDog']
10 print(names[3:-1])                             #这样-1就不会被包含了
11 #['Dog', 'Diaosi']
12 print(names[0::2])                             #后面的2是代表,每隔一个元素,就取一个
13 #['Breakering', 'Wolf', 'Diaosi']
14 print(names[::2])                              #和上句效果一样
15 #['Breakering', 'Wolf', 'Diaosi']
View Code

追加

1 #追加
2 names.append("Elephant")                       #在列表后面追加一个元素
3 print(names)
4 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant']
View Code

插入

1 #插入
2 names.insert(2,"SmallDingDing")                #在相应位置插入一个元素
3 print(names)
4 #['Breakering', 'Profhua', 'SmallDingDing', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant']
5 names.insert(5,"SmallDingDing")
6 print(names)
7 #['Breakering', 'Profhua', 'SmallDingDing', 'Wolf', 'Dog', 'SmallDingDing', 'Diaosi', 'FlyDog', 'Elephant']
View Code

修改

1 #修改
2 names[5] = "DiDog"
3 print(names)
4 #['Breakering', 'Profhua', 'SmallDingDing', 'Wolf', 'Dog', 'DiDog', 'Diaosi', 'FlyDog', 'Elephant']
View Code

删除

 1 #删除
 2 del names[5]
 3 print(names)
 4 #['Breakering', 'Profhua', 'SmallDingDing', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant']
 5 names.remove("SmallDingDing")
 6 print(names)
 7 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant']
 8 names.pop()
 9 print(names)
10 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog']
View Code

拓展

1 #拓展
2 names2 = ["Elephant","DiDog"]
3 names.extend(names2)
4 print(names)
5 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant', 'DiDog']
View Code

拷贝

 1 #拷贝
 2 new_names = names.copy()
 3 print(new_names)
 4 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant', 'DiDog']
 5 new_names = names[:]
 6 print(new_names)
 7 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant', 'DiDog']
 8 new_names = list(names)
 9 print(new_names)
10 #['Breakering', 'Profhua', 'Wolf', 'Dog', 'Diaosi', 'FlyDog', 'Elephant', 'DiDog']
View Code

统计

1 #统计
2 print(names.count("Breakering"))              #计数
3 #1
View Code

排序&翻转

 1 #排序&翻转
 2 names.sort()                                   #排序
 3 print(names)
 4 #['Breakering', 'DiDog', 'Diaosi', 'Dog', 'Elephant', 'FlyDog', 'Profhua', 'Wolf']
 5 names.reverse()                                #反转
 6 print(names)
 7 #['Wolf', 'Profhua', 'FlyDog', 'Elephant', 'Dog', 'Diaosi', 'DiDog', 'Breakering']
 8 #names3 = ["a","b","c",1,2,3]
 9 #names3.sort()
10 #Traceback (most recent call last):
11 # ................
12 #TypeError: unorderable types: int() < str()
View Code

获取下标

1 #获取下标
2 print(names)
3 #['Wolf', 'Profhua', 'FlyDog', 'Elephant', 'Dog', 'Diaosi', 'DiDog', 'Breakering']
4 print(names.index("FlyDog"))                    #只返回找到的第一个下标
5 #2
View Code

元组

元组其实跟列表差不多,也是存一组数,只不过它一旦创建,便不能再修改,所以又叫只读列表

1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 # Author:Breakering
4 names = ("Breakering","Profhua","Wolf")
5 print(names.index("Profhua"))
6 #1
7 print(names.count("Profhua"))
8 #1

字符串

  1 #!/usr/bin/env python3
  2 # -*- coding: utf-8 -*-
  3 # Author:Breakering
  4 name = "Breakering"
  5 name1 = "\t灵虚至尊"
  6 
  7 print(name.center(50,"*"))              #居中显示,不够用第二个参数填充
  8 #********************Breakering********************
  9 print(name.count("e"))                   #计算某个字符出现的次数
 10 #2
 11 print(name1.count(""))                   #计算某个字符出现的次数
 12 #1
 13 print("profhua".capitalize())             #首字母大写
 14 #Profhua
 15 print(name.casefold())                    #对Unicode时用casefold,它可以使所有语言的大写变小写
 16 #breakering
 17 print(name1.encode(encoding="utf-8"))       #编码,默认编码格式utf-8
 18 #b'\t\xe7\x81\xb5\xe8\x99\x9a\xe8\x87\xb3\xe5\xb0\x8a'
 19 print(name.endswith("g"))                  #判断某个字符串是不是以什么结尾
 20 #True
 21 print(name1.expandtabs(30))                 #将tab键转换为空格,默认是8个空格
 22 #                              灵虚至尊
 23 info = "my name is {}, and age is {}"
 24 print(info.format("Breakering",23))
 25 #my name is Breakering, and age is 23
 26 info = "my name is {0}, and age is {1}"
 27 print(info.format("Breakering",23))
 28 #my name is Breakering, and age is 23
 29 info = "my name is {name}, and age is {age}"
 30 print(info.format(name="Breakering",age=23))
 31 #my name is Breakering, and age is 23
 32 
 33 print(info.format_map({"name":"Breakering","age":23}))
 34 #my name is Breakering, and age is 23
 35 
 36 print(name.index("e"))                       #返回e所在字符串的索引
 37 #2
 38 print(name.isalnum())                        #是否是字母或数字
 39 #True
 40 print(name.isalpha())                        #是否是字母
 41 #True
 42 print(name.isdigit())                        #是否是数字
 43 #False
 44 print(name.isdecimal())                      #检查字符串是否只包含十进制字符
 45 #False
 46 print(name.isidentifier())                   #检测一段字符串可否被当作标志符,即是否符合变量命名规则
 47 #True
 48 print(name.islower())                        #是否是小写
 49 #False
 50 print(name.isnumeric())                      #如果 string 中只包含数字字符,则返回 True,否则返回 False
 51 #False
 52 print(" ".isspace())                         #是否是空格
 53 #True
 54 print("Bad Ass".istitle())                   #是否是标题,每个单词首字母大写即为标题
 55 #True
 56 print(name.isupper())                        #是否是大写
 57 #False
 58 print("+".join(["1","2","3"]))
 59 #1+2+3
 60 print(name.ljust(50,"-"))                     #左侧对齐,剩余填充
 61 #Breakering----------------------------------------
 62 print("BREAKERING".lower())                   #全部变小写
 63 #breakering
 64 print("     \nBreakering".lstrip())           #左侧去空格或者换行
 65 #Breakering
 66 
 67 #maketrans
 68 uper = "abcdefghij"
 69 out = "1234567890"
 70 trantab = str.maketrans(uper,out)              #先定义一个明文密码对应表
 71 msg = "this is a example!"
 72 print(msg.translate(trantab))                  #用明文密码对应表进行翻译
 73 #t89s 9s 1 5x1mpl5!
 74 
 75 print(name.partition("e"))                     #有点像 find()和 split()的结合体,从str出现的第一个位置起,把字符串string分成一个3元素的元组
 76 #('Br', 'e', 'akering')
 77 print(name.replace("e","1"))                   #替换
 78 #Br1ak1ring
 79 print(name.rfind("e"))                         #从左往右找,返回靠近右边的
 80 #5
 81 print(name.rindex("r"))                        #从左往右找,返回靠近右边的索引
 82 #6
 83 print(name.rjust(50,"."))                      #右对齐,剩余填充
 84 #........................................Breakering
 85 print(name.rpartition("e"))                    #以靠近右边的字符进行partition
 86 #('Break', 'e', 'ring')
 87 print(name.rsplit("e"))                        #就用split好了
 88 #['Br', 'ak', 'ring']
 89 print("Breakering\n      ".rstrip())           #右侧去空格或者换行
 90 #Breakering
 91 print(name.split("e"))                         #以什么字符进行分裂
 92 #['Br', 'ak', 'ring']
 93 print("a\nb\nc\nd".splitlines())               #以换行符进行分裂,可以适应不同操作系统
 94 #['a', 'b', 'c', 'd']
 95 print(name.startswith("B"))                    #是否以什么开头
 96 #True
 97 print(" \nBreakering\n    ".strip())           #去两头空格或者换行
 98 #Breakering
 99 print(name.swapcase())                         #大小写互换
100 #bREAKERING
101 print("bad ass".title())                       #将一个字符串变成标题
102 #Bad Ass
103 print(name.upper())                            #全部变大写
104 #BREAKERING
105 print(name.zfill(50))                          #右对齐,左侧用0填充
106 #0000000000000000000000000000000000000000Breakering

 

字典

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 # Author:Breakering
4 name_dict = {
5         "Breakering":23,
6         "Profhua":24,
7         "Wolf":25,
8         "Elephant":26
9          }

字典的特性:

  • dict是无序的                          PS:dict无序是因为dict没有下标
  • key必须是唯一的,so 天生去重
增加
1 #增加
2 name_dict["Dog"]=27
3 print(name_dict)
4 #{'Profhua': 24, 'Elephant': 26, 'Wolf': 25, 'Breakering': 23, 'Dog': 27}
View Code

修改

1 #修改
2 name_dict["Profhua"]=25
3 print(name_dict)
4 #{'Breakering': 23, 'Profhua': 25, 'Elephant': 26, 'Wolf': 25, 'Dog': 27}
View Code

删除

 1 #删除
 2 name_dict.pop("Dog")           #标准删除
 3 print(name_dict)
 4 #{'Profhua': 25, 'Wolf': 25, 'Breakering': 23, 'Elephant': 26}
 5 del name_dict["Wolf"]
 6 print(name_dict)
 7 #{'Elephant': 26, 'Profhua': 25, 'Breakering': 23}
 8 #name_dict.popitem()             #随机删除,尽量少用
 9 #print(name_dict)
10 #{'Breakering': 23, 'Profhua': 25}
View Code

查找

1 #查找
2 print("Breakering" in name_dict)  #标准查找
3 #True
4 print(name_dict.get("Breakering"))  #获取key的value,不存在返回None
5 #23
6 #print(name_dict["asdf"])           #此种查找,如果key不存在则会报错
View Code

多级字典嵌套及操作

 1 #多级字典嵌套及操作
 2 person_dict = {
 3         "Breakering":{"age":23,"city":"HZ"},
 4         "Profhua":{"age":24,"city":"SH"},
 5         "Wolf":{"age":25,"city":"SH"},
 6         "Elephant":{"age":26,"city":"SH"}
 7          }
 8 
 9 person_dict["Profhua"]["city"] = "ShangHai"
10 print(person_dict["Profhua"]["city"])
11 #ShangHai
View Code

其他用法

 1 #其他用法
 2 print(name_dict.values())
 3 #dict_values([23, 26, 25])
 4 print(name_dict.keys())
 5 #dict_keys(['Breakering', 'Elephant', 'Profhua'])
 6 name_dict.setdefault("Dog",28)        #给一个key设置一个默认值
 7 print(name_dict)
 8 #{'Elephant': 26, 'Breakering': 23, 'Dog': 28, 'Profhua': 25}
 9 a = {1:2,3:4}
10 name_dict.update(a)
11 print(name_dict)
12 #{'Dog': 28, 1: 2, 3: 4, 'Elephant': 26, 'Breakering': 23, 'Profhua': 25}
13 print(name_dict.items())
14 #dict_items([(1, 2), (3, 4), ('Breakering', 23), ('Elephant', 26), ('Profhua', 25), ('Dog', 28)])
15 
16 #formkeys
17 print(name_dict.fromkeys([1,2,3],"testd"))
18 #{1: 'testd', 2: 'testd', 3: 'testd'}
19 b = dict.fromkeys([1,2,3],["A","B","C"])
20 print(b)
21 #{1: ['A', 'B', 'C'], 2: ['A', 'B', 'C'], 3: ['A', 'B', 'C']}
22 b[1][1]="a"
23 print(b)
24 #{1: ['A', 'a', 'C'], 2: ['A', 'a', 'C'], 3: ['A', 'a', 'C']}
View Code

循环dict

1 #循环字典
2 #方法1
3 for key in name_dict:
4     print(key,name_dict[key])
5 
6 #方法2
7 for k,v in name_dict.items(): #会先把dict转成list,数据量大时莫用
8     print(k,v)

程序练习 

请闭眼写出以下程序。

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # Author:Breakering
 4 goods = [
 5         ["iphone",5800],
 6         ["mac pro",12000],
 7         ["ipad",4000],
 8         ["coffee",31],
 9         ["bag",2000],
10         ]
11 
12 if __name__ == "__main__":
13     shoppingcart = []
14     while True:
15         salary = input("Please input your salary:").strip()
16         if salary.isdigit():break
17         print("Please input num!")
18     while True:
19         for index,good in enumerate(goods):
20             print(index+1,good[0],good[1])
21         choose = input("Please make a choose:").strip()
22         if choose.isdigit() and int(choose)>0 and int(choose)<=len(goods):
23             if int(salary)<int(goods[int(choose)-1][1]):
24                 print("You don't have too much money!")
25                 continue
26             else:
27                 shoppingcart.append(goods[int(choose)-1])
28                 salary = int(salary) - int(goods[int(choose)-1][1])
29                 print("Added %s into your shoppingcart,and your left salary is \033[31;1m%s\033[0m"%(goods[int(choose)-1],salary))
30         elif choose == 'q':
31             print("You have got things below:")
32             for index1,buy_good in enumerate(shoppingcart):
33                 print(index1+1,buy_good[0],buy_good[1])
34             exit("Your left salary:\033[31;1m%s\033[0m"%salary)
35         else:
36             print("Wrong choose!Please try agian!")
37             continue

三、作业  

购物车程序:

  1. 启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额
  5. 在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
  6. 用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
  7. 允许查询之前的消费记录
posted @ 2017-04-03 16:23  Breakering  阅读(295)  评论(1编辑  收藏  举报