三天的Python课程

基础很sb但必须熟练掌握:

第一天就是Python的简单介绍与简单的接触。基本都是概念性的东西,需要知道一个非常便捷的IDE工具:pycharm,以后的编程就靠它了。还有就是%s和%d的格式化输出、运算符、及流程控制:if...else...;while...else...;for i in seq...else...

第二天的主要讲的是数据类型:数字,字符串,列表,元组,字典,集合及字符编码的详细介绍。

数字:转换为数字:  int(10);转换为浮点数:float(10.3) ;是否全部是数字:msg.isdigit()

字符串:切片:msg[1:7];长度:len(msg);成员运算(in or not in):print('a' in msg);查看索引:  print(msg.index(18));移除空白:msg.strip();切分split:msg.split('|');以...开头/结尾(startswith/endswith):print(msg.startswith('alex'));替换replace:print(msg.replace('a','B'));格式化输出%和format:  print('my name is %s my age is %s' %('egon',18))  print('my name is {} my age is {}'.format('egon',18));合成join:print(':'.join(l));是否全部由字母组成:print(msg.isalpha())
列表:列表可变:msg[0]='abc';切片:msg[1:4];长度:len(msg);成员运算(in or not in):print('a' in msg);追加:msg.append('abc');删除:del msg[1]  msg.remove('abc')  msg.pop(1);插入:msg.insert(index,'abc');扩展添加:msg.extend([1,2,3,4]);清空列表:msg.clear();复制:msg.copy();反转:msg.reverse()

元组:切片:msg[1:7];长度:len(msg);成员运算(in or not in):print('a' in msg);查看索引:  print(msg.index(18));统计元素个数:  print(ages.count('abc'))

字典:增加:  info['hobbies']=['read','music','play','sleep','eat'] ;长度:len(msg);key运算(in or not in):print('a' in msg);删除:print(info.pop('name'));  键keys():   print(info.keys());值values():  print(info.values());键值对items():print(info.items());获取值:print(info.get('name123',123));删除键值对:  print(info.popitem());没有则新增,有则返原值:print(info.setdefault('hobbies',['read','music']));更新字典(字典):info.update(info_new);

集合:长度:len(msg);成员运算(in or not in):print('a' in msg);并集:|;交集:&;差集:-;对称差集:^;父集,子集:>,>= ,<,<= 

字符编码:  unicode =====encode ======>gbk # 存文件,unicode可以转化成任意编码    gbk====decode====>unicode 

 1 #打印三级菜单,打印下级时,记录到列表中;打印上级时,用pop取出,然后再打印最后字典的key
 2 menu = {
 3     '北京':{
 4               '海淀':{'五道口':{'soho':{},'网易':{},'google':{}},
 5                         '中关村':{'爱奇艺':{},'汽车之家':{},'youku':{}},
 6                         '上地':{'百度':{},},
 7                        },
 8               '昌平':{'沙河':{'老男孩':{},'北航':{},},
 9                           '天通苑':{},'回龙观':{},
10                        },
11         '朝阳':{},
12         '东城':{},
13             },
14     '上海':{
15               '闵行':{"人民广场":{'炸鸡店':{}}
16                        },
17               '闸北':{'火车战':{'携程':{}}
18                        },
19               '浦东':{
20                        },
21               },
22     '山东':{
23              },
24    }
25 
26 exit_flag = False
27 current_layer = menu
28 
29 layers = [menu]
30 
31 while not  exit_flag:
32     for k in current_layer:
33         print(k)
34     choice = input(">>:").strip()
35     if choice == "b":
36         current_layer = layers[-1]
37         #print("change to laster", current_layer)
38         layers.pop()
39     elif choice not  in current_layer:continue
40     else:
41         layers.append(current_layer)
42         current_layer = current_layer[choice]
 #打印购物车程序 以列表的索引为主
1
#!/usr/bin/env python2 2 import sys 3 salary = int(raw_input('please input you salary:')) 4 products = [ 5 ['Iphone',5800], 6 ['MacPro',12000], 7 ['NB Shoes',680], 8 ['Cigarate',48], 9 ['MX',2500] 10 ] 11 shopping_list = [] 12 13 while True: 14 for p in products: 15 print products.index(p),p[0],p[1] 16 choice = raw_input("33[32;1mPlease choose something to buy:33[0m").strip() 17 if choice == 'quit': 18 print "You hava bought below stuff:" 19 for i in shopping_list: 20 print ' ',i 21 sys.exit('Goodbye!') 22 if len(choice) == 0:continue 23 if not choice.isdigit():continue 24 25 choice = int(choice) 26 if choice >= len(products): 27 print "33[31;1mCloud not in the range!33[0m" 28 continue 29 pro = products[choice] 30 if salary >= pro[1]:#mean you can afford this 31 salary = salary - pro[1] 32 shopping_list.append(pro) 33 print "33[34;1mAdding %s to shopping list,you have %s left.33[0m" % (pro[0],salary) 34 else: 35 print "33[31;1mThe price of %s is %s,yet your current balance is %s,so try another one.33[0m" % (pro[0],pro[1],salary) 36

第三天是文件处理和函数基础,感觉有点难度了。

# 文件的处理机制

#打开
f=open('a.txt',mode='r',encoding='utf-8') #变量赋值
#读/写
data=f.read()
print(data)
#关闭
del f #回收python资源,python回收机制自动处理,不用写
f.close() #回收操作系统的资源
del f
print(f)

#流程分析:

#1:向操作系统发起系统调用
#2:操作系统打开这个文件,返回一个文件句柄给应用程序
#3: 在应用程序中把文件句柄赋值给一个变量

#注意两点:

#1:打开一个文件对应两部分,一个Python级别的文件句柄,另外一个是操作系统打开的文件(默认
# 打开文件的编码是以操作系统的编码为准的,除非open()指定encoding='编码'
#2:当文件操作完毕后,应该回收两部分资源,
#del f:回收应用程序资源(python解释器自动的垃圾回收机制已经替我们做了)
#f.close:回收操作系统
#上下文管理with 自动关闭系统的占用f.close()
with open('a.txt',mode='r',encoding='utf-8') as f:
print(f.read())

# 文件打开的模式

#r:默认的打开模式,只读,文件不存在则报错rt:txt

f=open('a.txt',encoding='utf-8') #默认就是只读模式
print('===>',f.read()) #读所有,bytes---decode('utf-8')--->unicode(str) 从硬盘读出来就是bytes类型,read出来是python的字符串就是unicode,python3的字符串是unicode
print(f.readlines()) #读所有,结果放入列表中
print(f.readline(),end='') #一次读一行 print函数默认有个换行符' '
f.close()

#w:只写模式,如果文件存在则清空,如果文件不存在则新建

#a:追加写模式,如果文件存在则把光标移动到文件末尾,如果文件不存在则新建

#b:以bytes的形式去操作文件内容,不能指定编码 只有字符串类型才有编码

with open('a.txt',mode='rb') as f:
data=f.read()
print(data.decode('utf-8')) #bytes类型转成字符串unicode

#了解部分
print(f.readable()) #判断文件是否可读
print(f.writable()) #判断文件是否可写
f.closed() #文件是否关闭
f.encoding() #如果文件打开模式为b,则没有该属性
f.flush() #立刻将文件内容从内存刷到硬盘
f.name() #查看文件名

#以文本t的模式读文件,n代表的是字符的个数,读3个字符,其他都是字节

#以b的模式读文件,n代表的是字节的个数

#tell:告诉当前光标的位置

#seek:移动光标

  #0:文件开头 可以b模式,也可以t模式
  #1:当前位置 只能基于b模式
  #2:文件末尾 只能基于b模式

 1 #tail -f access.log 
 2 import time
 3 with open('access.log','rb') as f:
 4     f.seek(0,2)
 5     while True:
 6         line=f.readline()
 7         if line:    #读到就打印 没有读到就sleep一下
 8             print(line.decode('utf-8'),end='')
 9         else:
10            time.sleep(0.2)

#truncate 截断文件 写操作 r模式就报错 w就没有截断这一说直接清空了 只能a模式,就文件开头开始,后面删掉

#文件的修改 硬盘上的内容没有改这一说,直接就是新的内容直接覆盖掉老的文件,会生成新文件.swap,然后删除原文件,重命名至原文件。内存可以改

#方式一(占用内存过大,仅适用于小文件):把硬盘中文件的数据全部读入内存,然后在内存里进行修改,最后保存

import os
with open('e.txt','r',encoding='utf-8') as read_f,
        open('.e.txt.swap','w',encoding='utf-8') as write_f:
    data=read_f.read()
    # print(type(data))  #str
    data=data.replace('alex','SB')
    write_f.write(data)

os.remove('e.txt')
os.rename('.e.txt.swap','e.txt')

  #方式二:一行一行地读,一行一行地改

1 import os
2 with open('e.txt','r',encoding='utf-8') as read_f,
3         open('.e.txt.swap','w',encoding='utf-8') as write_f:
4     for line in read_f:
5         line=line.replace('SB','alex')
6         write_f.write(line)
7 
8 os.remove('e.txt')
9 os.rename('.e.txt.swap','e.txt')

函数基础的网址:http://www.cnblogs.com/DemonAngel/p/7581862.html


 

本文是作者本人的笔记心得,如果有bug请评论留言; 如果本文对你有帮助,请点击【好文要顶】和【关注我】以示鼓励; 大家也可以关注我的微信订阅号【ysgxming】一起交流学习。
原文地址:https://www.cnblogs.com/DemonAngel/p/7581717.html