Python小结

【exit】

退出程序

【%】

占位符         %s 【string】  %f【float】  %d【int】

【自动换行】

python 2.X 版本使用逗号分割可以使print不换行 【print "hello",】

python 3.X版本利用end方法可以使print不换行 【print ("hello ",end="")】

【while】

while结尾可以使用else,当程序执行完毕时,再执行else

输出100之内偶数和  ??

x=0
sum =0
while True:
    x+=1
    if x%2==0:
        continue
    if x>100:
        break
    sum+=x
print sum


运行结果:
2500

【for】

for i  in  序列

输出99乘法表  ??

sum =0
for i in range(1,10):
    l = []
    for j in range(1,i+1):
        sum = i*j
        s= str(i)+"*"+str(j)
        c= s+"="+str(sum)
        # l.append(c)
        if i==j:
            print c
        else:
            print c,


运行结果:

1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

【list列表】

【增】

list.append()     默认添加到末尾              list.insert(索引,“元素”)    添加到指定的索引             

list.extend(list1) 将两个列表合成一个

a = []
b=["4","5"]
a.append("1")
a.append("2")
a.insert(1,"3")
a.extend(b)
print a


运行结果:
['1', '3', '2', '4', '5']

【删】

list.remove()    删除指定的元素        list.pop(索引,"元素")    删除指定的元素,有返回值         list.del()  什么都可以删除,包括这个对象           list.clear()    清空list 

a =[1,2,3,4,5,6]
a.remove(1)
b=a.pop(2)
print a
print b


运行结果:
[2, 3, 5, 6]
4

【改】 

list[索引] = "x"  #通过对索引位置重新赋值,达到更改元素内容的目的

【查】

  list.count(元素)  查找列表中同一元素的个数            list.index(元素) 查找列表的的元素索引值

【sort】

没有返回值

数字按照从小到大排序,字符按照Ascll排序

【reverse】

list 反序摆列

a=[1,3,2,5,6,2]
a.sort()
print a
b=a.count(2)
print b
a.reverse()
print a


运行结果:

[1, 2, 2, 3, 5, 6]
2
[6, 5, 3, 2, 2, 1]

【list切片】

name[n:m]  切片是不包含后面那个元素的值(顾头不顾尾)

name[:m] 如果切片前面一个值缺省的话,从开头开始取

name[n:] 如果切片后面的值缺省的话,取到末尾

name[:] 如果全部缺省,取全部

name[n:m:s] s:步长  隔多少个元素取一次

步长是正数,从左往右取

步长是负数,从右往左取

注:切片同样适用于字符串,字符串也有下标

 L[4:50:5]#从索引4开始,每个5位取一个,取到索引50结束,50索引不包含

r=[1,2,3,4,5,6,7,8,9,10]
l=range(4,50)
print l[4:50:5]
print r[8::-2]


运行结果:

[8, 13, 18, 23, 28, 33, 38, 43, 48]
[9, 7, 5, 3, 1]

【enumerate】

一个可以添加索引值的方法 enumerate(list,1)

【dict】

【增】

dict【元素】=*** 元素有就修改,没有就添加           dict.setdefault('','') 键存在就不改动,返回相应的值,键不存在,增加新的键值对,并返回相应的值

【删】

del dict(键) 删除键值对       pop(键) 删除返回值       popitem(键)   随机删除一个键值对      clear() 清空    del dict  删除字典

b={2:"3",4:"5",6:"7"}
b[2]="1"
b.setdefault(8,"9")
c=b.pop(4)
print c
print b
b.clear()
print b


运行结果:
5
{8: '9', 2: '1', 6: '7'}
{}

【查】

dict.key() 键             dict.value() 值        dict.Iteme()键值对          in() 查询是否存在值           get(key)   查询键        get(键,值) 如果有就返回值。没有返回后边的值

【改】

dict.update(dict1) 有就更新,没有添加

b={2:"3",4:"5",6:"7"}
print b.keys()
print(b.values())
print list(b.iteritems())
c={1:"a"}
b.update(c)
print  b




运行结果:

[2, 4, 6]
['3', '5', '7']
[(2, '3'), (4, '5'), (6, '7')]
{1: 'a', 2: '3', 4: '5', 6: '7'}

【set列表】

可以使用大括号 { } 或者 set() 函数创建集合

注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

set列表是无序排列的(可以包含前边所有的列表的格式)

set.remove(删除)   set.pop()  删除返回值(python2 删除的是第一个,python3 删除是随机的)      set.discard()   删除       set.update()    有就不修改,没有就更新
set.add(添加)    set.isdisjiont()    查看是否有相同元素,有返回false ,没有返回True

set.difference  (set1)   找出两个列表中的不同元素     set.difference_update(set1)    找出不同并更新   (a-b)

set.interesection(set1)   找出相同的元素           set.interesection_update(set1)        找出相同更新    (a&b)

set.union(set1)    相当于数学中的并集   (a|b)            set.symmetric_difference(set1)     取出相同的部分,显示所有的不同

set.issubset()   子集           set.issuperset()    父集

a={"hello","alex",123,"cv","oo"}
b = {"hello","tom"}
a.discard("oo")
print a.difference(b)
print a-b
# print a.difference_update(b)
print a
print a.isdisjoint(b)
print a&b
print a.union(b)
print a.symmetric_difference(b)


运行结果:

set([123, 'alex', 'cv'])
set([123, 'alex', 'cv'])
set([123, 'alex', 'hello', 'cv'])
False
set(['hello'])
set(['alex', 'tom', 123, 'hello', 'cv'])
set([123, 'alex', 'cv', 'tom'])

  

【字符串】

【format】 格式化输出

‘’.join(【a,b,c】)

center(50,'')

str = "hello"
print (str.center(50,"*"))

s = "hello {name}"
s.islower()
print s.format(name="tom")
print "".join([str," Bob"])



运行结果:

**********************hello***********************
hello tom
hello Bob

【endswith() / startswith】 以什么开头/结尾      【find】 查找元素返回索引值      【isdigit】判断是否是数字      【islower/ isupper】 判断是否全大写/ 小写

【strip】 删除左右的空格,换行符           【replace】 替换             【split】 分割符                 【expandtabs】 制作表格

【占位符】

占位符:%s 【string】 %f【float】 %d【int】   

【编写函数:def】


【列表生成式for 可以添加筛选条件,可以添加多层嵌套循环】

return [x.upper() for x in L if isinstance(x,str)]

isinstance()判断是否是字符串 upper()字母大写

【文件】

  with open("text","r") as read:

  data = read.readlines()     推荐使用这种打开方式 ,可以不用close(),避免再打开文件后忘记close()

【open() 】 打开文件        

   'r':读

   'w':写

   'a':追加

   'r+' == r+w(可读可写,文件若不存在就报错)

   'w+' == w+r(可读可写,文件若不存在就创建)

   'a+' ==a+r(可追加可写,文件若不存在就创建)

    对应的,如果是二进制文件,就都加一个b就好啦:

    'rb'  'wb'  'ab'  'rb+'  'wb+'  'ab+'

【read()】 读取文件 【 write()】 写入文件 【 tell() 】 获取光标的位置 【seek()】 移动光标

【flush】 刷新缓存区,立即写入磁盘   【truncate()】 数据截断 “w” 没有太大意义 “a” 可按要求截断

 import sys,time
 for i in range(30):
     sys.stdout.write("*")
     sys.stdout.flush()
     time.sleep(0.1)

运行结果:
可以简易的实现进度

【练习】

1.模拟购物

salary = raw_input("salary is:")
if salary.isdigit():
    shop=[]
    pice1 = [["iphone x","5899"],["max book","4999"],["bicyke","1600"],["python","80"]]
    pice = ["5899","4999","1600","80"]
    for i,v in enumerate(pice1,1):
        print (i,v)
    data = '''
    ---------价格表-------
    1.iphone x :5899
    2.max book :4999
    3.bicyke :1600
    4.python :80
    '''
    print(data)
    print("请输入你要买的东西,如想退出请输q")
    while salary>0:
        i= raw_input(">>>:")
        if (i == "q"):
            print ("已购买:%s" % (shop))
            print ("余额:%s" % (salary))
            break
        if int(salary)>=int(pice[int(i)-1]):
            shop.append(pice1[int(i)-1])
            salary=int(salary)-int(pice[int(i)-1])
            print("余额:%s"%(salary))
        else:
            print("余额不足")




运行结果:


salary is:9999
(1, ['iphone x', '5899'])
(2, ['max book', '4999'])
(3, ['bicyke', '1600'])
(4, ['python', '80'])

    ---------价格表-------
    1.iphone x :5899
    2.max book :4999
    3.bicyke :1600
    4.python :80
    
请输入你要买的东西,如想退出请输q
>>>:1
余额:4100
>>>:3
余额:2500
>>>:4
余额:2420
>>>:1
余额不足
>>>:q
已购买:[['iphone x', '5899'], ['bicyke', '1600'], ['python', '80']]
余额:2420

2.

三级菜单:

data = {
    "山东省":{
        "临沂市":{
            "沂南":{},
            "蒙阴":{}
        },
        "烟台市":["海阳市","牟平市"]
    },
    "河南省":{
        "郑州市":["老河口市","牧原市"]
    }
}
menu = data
parent = []
while True:
    for i in menu:
        print i
    choice = raw_input("请选择:").strip()
    if len(choice)==0:
        continue
    if choice in menu:
        parent.append(menu)
        menu = menu[choice]

    elif choice=="b":
        if parent:
            menu=parent.pop()
    else:
        print ("查无此项")



运行结果:

山东省
河南省
请选择:山东省
临沂市
烟台市
请选择:临沂市
沂南
蒙阴
请选择:沂南
请选择:b
沂南
蒙阴
请选择:b
临沂市
烟台市
请选择:b
山东省
河南省

 3

简易进度:

import sys,time
for i in range(30):
    sys.stdout.write("*")
    sys.stdout.flush()
    time.sleep(0.1)


运行结果:
原文地址:https://www.cnblogs.com/guo970910/p/9916758.html