Python

------------------------------while循环------------------
#!/usr/bin/python3


old_age=30
count=0
while count<3: #或者count<3 的时候执行


    if count == 3:
        print("你已经猜了3次了结束了:", count)
        break
    age=int(input("age:"))
    if old_age==age:
        print("猜对了")
        break
    elif age>old_age:
        print("大啦!!")
    else:
        print("小啦!!")
        count = count + 1
else: #这里与while 配合使用,<3的时候在while循环里面,>3的时候在else执行
    print("you have tried too many times . fuck you ")


    count=0
while True:
    print("参数",count)
    count=+1
-------------------------------for循环----------------------------
#for循环
for i in  range(10):
    print("loop",i)


for i in  range(1,10,2):
    print("tiao:",i)
-------------------------pyc是什么------
Python的原始代码在运行前都会被先编译成字节码,并把编译的结果保存到一个一个的PyCodeObject中,
pyc 文件即是把PyCodeObject从内存中以marshal格式保存到文件后的结果。


----------------------python数据类型----------------------------------------------
type(name) //查看name的数据类型
Int 整数 数据存超了了就自动变为长整形
long 长整数


特别注意:python3已经没有长整型了 只有一个数据类型了


float 浮点型
complex 复数  //用不到 工程类用的多
布尔值 1或0
字符串 "hello"


a=0
if a:print('a') //判断a是否为真,真的话就打印


--------------------入门知识拾忆------------------------------
三元运算
result=值1 if 条件 else 值二
d=a if a>b else c  //如果a>b 结果=a ,否则就是c


进制:
二进制
八进制
十进制(生活使用)
十六进制


--------------------------bytes数据类型---------------------------------
decode  //解码
encode  //编码
string   <--转换-->   bytes




msg="美国人"
print(msg.encode(encoding='utf-8'))  //转为二进制  ”utf-8“ 告诉原来的数据类型是utf-8 
print(msg.encode(encoding='utf-8').decode()) //转回来














-------------------------列表的使用----1-----------------------------------
names=['张扬',"中国","张飞","关羽"]
names.append("李磊") #追加
names.insert(1,"李白")  #插入在下标是1的位置


print(names[4]) #取一个值
print(names[0],names[1])
print(names[1:3]) # 切片  其实位置包括,结束位置不包括
print(names[-1]) #取最后一个  倒着数
print(names[-2]) #取倒数第二个  倒着数
print(len(names))
print(names[-2:-1])
print(names[-2:])
print(names[:3])


#修改
names[0]="小粒"
print(names[0])


#删除
names.remove("小粒") #第一种删除
print(names[0])


del names[0]  #第二种删除
print(names[0])


names.pop()#删除最后一个 不输入下标默认删除最后一个
names.pop(1) #删除下标为1的值


names.index("关羽") #根据名字照着索引的位置  查找
print(names.index("关羽"),"pp")
print(names[names.index("关羽")])
print(names.count("关羽")) #统计有几个关羽


#names.clear() #清除整个列表
names.reverse() #整个列表反转
names.sort()  #排序


names2=["1","3""00"]
print(names)
names.extend(names2) #把names2合并到names里面
print(names)




-------------------------列表的使用----2-----------------------------------
import  copy
names=['张扬',"中国","张飞",["11","22"],"关羽"]  #加一个子列表
#names2=names.copy();  #浅复制 浅copy copy第一层,没有copy内存地址
#names2=copy.copy(names) #  copy.copy(names)=names.copy()
names2=copy.deepcopy(names)#深入copy 内存地址映射
print(names)
print(names2)
names[2]="祥鹏"


names[3][0]="下牛" #把names里面的子集11修改成下午
print(names)  # ['张扬', 'china', '张飞', ['下牛', '22'], '关羽']
print(names2) # ['张扬', '中国', '张飞', ['下牛', '22'], '关羽']




#列表的循环
for i in names:
    print(i)


# 从第一个开始到最后一个 0表示第一 ,-1表示最后一个,0and1可以省略 每个2个取出来
names3=['张扬',"中国","张飞",["11","22"],"关羽"]
print(names3[0:-1:2])  #等于range(0,10,2)
#print(names3[::2])


-----------------------------浅copy---------------------------------------


import copy
#浅copy的作用和场景
person=['name',['saving',1000]] #模板 name:姓名,saving:存款
'''
#浅copy有三种
p1=copy.copy(person)
p2=person[:]
p3=list(person) #工程函数
'''
p1=person[:]
p2=person[:]
#比如夫妻关系 共同存款
p1[0]="张三"
p2[0]="张三媳妇"
print(p1)
print(p2)
#浅copy用来创建联合账号这种情况的场景
p1[1][1]=500
print(p1)
print(p2)


--------------------------------元组-----和列表一样存东西(创建完后只读不可以修改)但我们可以对元组进行连接组合--------------------------------


name=('jack','mayy','poney')
它只有两个方法一个是count,一个是index


元组中只包含一个元素时,需要在元素后面添加逗号
tup1 = (50,);


tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');


# 以下修改元组元素操作是非法的。
# tup1[0] = 100;


# 创建一个新的元组
tup3 = tup1 + tup2;
print tup3;


#删除元组
del tup;


元组内置函数


1 cmp(tuple1, tuple2)
比较两个元组元素。
2 len(tuple)
计算元组元素个数。
3 max(tuple)
返回元组中元素最大值。
4 min(tuple)
返回元组中元素最小值。
5 tuple(seq)
将列表转换为元组。




----------------------购物车练习--------------------------------------
__author__ = "Alex Li"




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)
    while True:
        for index,item in enumerate(product_list):
            #print(product_list.index(item),item)
            print(index,item)
        user_choice = input("选择要买嘛?>>>:")
        if user_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) )
                else:
                    print("\033[41;1m你的余额只剩[%s]啦,还买个毛线\033[0m" % salary)
            else:
                print("product code [%s] is not exist!"% user_choice)
        elif user_choice == 'q':
            print("--------shopping list------")
            for p in shopping_list:
                print(p)
            print("Your current balance:",salary)
            exit()
        else:
            print("invalid option")




--------------------------------字符串的常用操作-----------------------------------


name="doutao is \tiio are {name} 和 {age}"
print(name.capitalize())  #把第一个字母大写
print(name.count("o")) #统计有2个o
print(name.center(10,"-"))#一共打印10个字符,不够的用 - 补上
print(name.endswith("ao")) #判断name是否以ao结尾
print(name.expandtabs(tabsize=20)) #吧\t转换为20个空格的长度
print(name.find("is")) #查找is起始位置索引
#还可以切片 print(name[name.find("is"):])
print(name.format(name="张三",age=30)) #格式化
print(name.format_map({"name":"张三","age":30})) #字典 这个格式很少用


print("abs2388".isalnum()) #判断是否阿拉伯字符(a-z加上1-9都可以,其他特殊字符就不是返回false)
print("aLL".isalpha()) #是否纯英文字符
print("1".isdigit()) #是否整数
print("1D".isidentifier()) #判断是不是一个合法的标识符(合法的变量名称)
print("122".isnumeric())  #判断是否一个数字
print("My Name Is. Dt".istitle())  #每个字母第一个是大写条件成立
print("+".join(["a","b","c"])) #结果a+b+c 类似Java 等split
print(name.ljust(50,"*"))  #结果 doutao is iio are {name} 和 {age}*****************
print(name.rjust(50,"*")) #结果 *****************doutao is iio are {name} 和 {age}
print("HHOOP".lower()) #变小写
print("aaa".upper())  #变大写
print("\nAAPP".lstrip()) #去左边空格
print(" ppll ".strip()) #去两边空格


p=str.maketrans("abcdefg","1234567") #1对应a ,b对应2,c对应3....类推
print("alike".translate(p))# 这里的a就经过p 翻译    对应成1 其他没有的就是原来的字符 有的就被翻译


print("abcaf".replace("a","123")) #替换全部a
print("abcaf".replace("a","123",1)) #只替换一个位置的a
print("aknnal".rfind("a")) #找到最右边那个a的下标返回


print("aa+pp+ll ,,".split("+")) #结果 ['aa', 'pp', 'll ,,']
print("a+\na+c".splitlines()) #按照换行符号来分 ['a+', 'a+c']
print("aoopp".startswith("a"))


------------------------------字典-----------------无序---------------------------------


#字典
info={
    "stu01":"张三",
    "stu02":"李四",
    "stu03":"王武",
    "stu04":"王修",
}
#del info["stu04"] #删除 方法一
#info.pop("stu03") #删除 方法二
print(info)
info["stu01"]="武藤兰" #修改 如果stu001存在就修改,不存在就添加一条数据
print(info["stu01"]) #查找 该方法查到没有的值就会报错
print(info.get("stu09")) #查找 查不到不会报错
print("stu01" in info ) #判断是否包含在info 里面


#多级字典嵌套及操作
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
>>> info.values()
dict_values(['LongZe Luola', 'XiaoZe Maliya'])


#keys
>>> info.keys()
dict_keys(['stu1102', 'stu1103'])




#setdefault  去取值如果取到就返回,没取到就创建一个新的值
>>> info.setdefault("stu1106","Alex")
'Alex'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> info.setdefault("stu1102","龙泽萝拉")
'LongZe Luola'
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}




#update  两个集合如果有key相同就修改,没有就添加(也就是将两个集合合并)
>>> info
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
>>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
>>> info.update(b)
>>> info
{'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}


#items #字典转为列表
info.items()
dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])


#初始化一个新的字典 key已经写好了
#通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
>>> dict.fromkeys([1,2,3],'testd') #创建三个新的key(1,2,3) 默认值是value ="testd"
{1: 'testd', 2: 'testd', 3: 'testd'}






#循环字典
for i in info: #推荐
    print(i,info[i])
print("--------------")
for k,v in info.items():
    print(k,v)












---------------------------------------第三周--------------------------------------------------
---------------------------------------集合----无序的------------------------------------------
list_1=[1,4,5,7,3,6,7,9]
list_1=set(list_1) #  把list_1 变成集合 就没有重复的数据了
list_2=set([2,3,6,0,66,22,8,4])  #集合2
'''print(list_2)
print(list_1,type(list_1)) #运行结果 {1, 3, 4, 5, 6, 7, 9} <class 'set'>


#集合交集
print(list_1.intersection(list_2))


#并集 合并起来,去掉重复的数字
print(list_1.union(list_2))


#差集 比如我有你没有 list_1里面list_2没有的
print(list_1.difference(list_2))


#子集
print(list_1.issubset(list_2))
list_3=set([1,3])
#父集
print(list_3.issubset(list_1))




#反向差集 或者对称差集 也就是两个互相没有的取出来
print(list_1.symmetric_difference(list_3))


list_4=set([5,6,7,8,1]) #有交集就False 没有交集就True
print(list_3.isdisjoint(list_4))
'''


#交集
print(list_1 & list_2)
#并集
print(list_2 | list_1)


#差集
print(list_1-list_2)


#对称差集
print(list_1 ^ list_2)




print(list_1)
list_1.add(999)#添加
list_1.update([777,888]) #修改
print(list_1)


print(list_1.pop()) #删除
#print(list_1.remove("ww")) #删除没有的会报错
print(list_1.discard("ww")) #删除没有的不会报错




----------------------------------------------文件操作--------------------------------------------


#读写是分开的 ,要么读,要么写(r 读,w 写,a追加)
#打开文件 读
''' 
f=open("yesterday","r",encoding="UTF_8") #文件句柄 (文件的内存对象,大小,内容,内存地址)
data = f.read() #读文件
print(data)
'''
#写文件
#f=open("yesterday2","a",encoding="UTF_8") #文件句柄 (文件的内存对象,大小,内容,内存地址)
#f.write("我爱北京\n") #\n 换行
#f.write("天安门\n")
#f.close()


#一行一行读取
#f=open("yesterday","r",encoding="UTF_8")
#print(f.readline())
#print(f.readline())


#循环读取全部
#for i in f.readlines():  #readlines()是个列表
#    print(i.strip())  # strip() 去掉空格和换行




#enumerate 可以打印下标  f.readline只适合读小文件
'''for index,i in  enumerate(f.readlines()):
    if index==9:
        print("-------------")
        continue
    print(index,i.strip())
'''


#高效 以后就用这种读
f=open("yesterday","r",encoding="UTF_8")
for line in f:  #效率最高读一行放到内存 ,清除在读一行 ,不会发生内存溢出
    print(line)










##########################flush()演示#####
import sys,time


for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush() #使用flush强制刷新到存储,不然会
    time.sleep(0.1)




>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>写读模式没有啥暖用 知道就行


#f=open("yesterday","r+",encoding="UTF_8") # r+ 表示读写
#print(f.readline())
#print(f.readline())
#print(f.readline())
#print(f.readline())
#print(f.tell()) #打印光标在什么位置(也就是指针)
#f.write("---------------6---------------\n")




#f=open("yesterday","a+",encoding="UTF_8") #  最佳写(此时不能读)
#f1=open("yesterday","rb") #以二进制形式读取文件
#f1.write("kkklll".encode()) #以二进制写 加上.encode()


f=open("yesterday","w+",encoding="UTF_8") # r+ 表示写读(只能先写在读)  区别是他是先创建一个文件在写
f.write("-----------8-----------\n")
f.write("-----------8-----------\n")
f.write("-----------8-----------\n")
f.write("-----------8-----------\n")
f.write("-----------8-----------\n")
print(f.tell()) #光标位置
f.seek(10) #指针回到10这个位置
print(f.readline())
f.write("this is my end ")
f.close()


-------------------------------文件的修改-------------------------------------
只能把旧文件读出来在合适的位置插入新文件,再把新文件改成旧文件 Python只能这种
f=open("yesterday","r",encoding="utf-8")
f_new=open("yesterday_bak","w",encoding="utf-8")


for line in f:
    if "我会跟着唱" in line:
        line=line.replace("我会跟着唱","我会跟着唱 HELLO")
    f_new.write(line)
f.close()
f_new.close()













































































  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值