python第二天学习笔记

Python文件处理

文件内容替换

for line infileinput.input(“filepath”,inplace=1):

line=line.replace(“oldtest”,”newtest”)

print line,

//包含oldtest的替换成newtest

例子:

[email protected]:~/python$vim finput.py

#!/usr/bin/env python

import fileinput

for line infileinput.input("contact_list.txt",backup=‘bak‘,inplace=1):

line = line.replace(‘wang‘,‘chao‘)

print line,

//将文件中wang改成chao,并将原文件备份一份bak文件

程序运行结果

[email protected]:~/python$python finput.py

[email protected]:~/python$ls

contact_list.txtbak

修改某行

with open(“foo.txt”,”r+”) as f:

old=f.read()#read everything in the file

f.seek()#rewind

f.write(“new line\n”+old)#write the new

line before

例子:

[email protected]:~/python$vim fseek.py

#f = open(‘contact_list.txt‘,‘r+‘)

withopen(‘contact_list.txt‘,"r+") as f :

old = f.read()

f.seek(14)

f.write("new line\n")

//f.seek(14),文件从第14个字符开始加newline,并换行

程序运行结果

[email protected]:~/python$more contact_list.txt

1 cai  chengxnew    1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

[email protected]:~/python$python fseek.py

[email protected]:~/python$more contact_list.txt

1 cai  chengxnew line

85

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

[email protected]:~$ vimtest.txt

[email protected]:~/python$python

>>> f=file(‘test.txt‘)                 //打开只读模式

>>> f=file(‘test.txt‘,‘w‘)              //打开可写

>>> f.write(‘hello world!‘)            //写入

>>> f.flush()                       //文件新建或被保存

>>> f.close()

>>> f=file(‘test.txt‘,‘a‘)

>>> f.write(‘AAA‘)                  //追加内存

[email protected]:~/python$cat test.txt

hello world!AAA

python列表

处理和存放一组数据

用途:购物列表、工资列表……

语法:ShoppingList =[‘car’,’clothes’,’iphone’]

添加book到ShoppingList列表:shoppingList.append(‘book’)

删除car:          ShoppingList.remove(‘car’)

删除最后一个:     ShoppingList.pop()

删除列表中第二个内容:ShoppingList.pop(1)

[email protected]:~/python$python

>>>nameList=[‘wang‘,‘cai‘,‘ru‘,‘yao‘]

>>> nameList

[‘wang‘, ‘cai‘, ‘ru‘, ‘yao‘]

>>> nameList[2]               //取出2号,从0开始数

‘ru‘

>>> nameList[-1]               //取出最后一个

‘yao‘

>>> nameList.append(‘fei‘)       //加入fei

>>> nameList

[‘wang‘, ‘cai‘, ‘ru‘, ‘yao‘, ‘fei‘]

>>> nameList.insert(2,‘sun‘)       //在2号前插入sun

>>> nameList

[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘, ‘fei‘]

>>> nameList.count(‘wang‘)       //统计wang出现的个数

1

>>> ‘cai‘ in nameList          //判断cai是否在列表中

True

>>> nameList

[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘, ‘fei‘]

>>> nameList.index(‘fei‘)       //索引,fei在列表中的位置

5

>>> nameList.pop()           //删除最后一个

‘fei‘

>>> nameList

[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘]

>>> nameList.remove(‘Y‘)         //删除一个元素Y,如果其中有两个Y,将只删除前面一个

>>> nameList.reverse()           //排序

>>> nameList

[‘yao‘, ‘ru‘, ‘sun‘, ‘cai‘, ‘wang‘]

>>> nameList.reverse()           //排回

>>> nameList

[‘wang‘, ‘cai‘, ‘sun‘, ‘ru‘, ‘yao‘]

>>> nameList.sort()             //按字母排序

>>> nameList

[‘cai‘, ‘ru‘, ‘sun‘, ‘wang‘, ‘yao‘]

>>> nameList.extend(‘hello world‘)

>>> nameList

[‘cai‘, ‘ru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘h‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]

>>> nameList[1]=‘ruru‘                          //修改1号为ruru

>>> nameList

[‘cai‘, ‘ruru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘h‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]

>>> nameList.index(‘h‘)                         //查找h所在的位置

5

>>> i=nameList.index(‘h‘)

>>> nameList[i]=‘H‘                              //将h改成H

>>> nameList

[‘cai‘, ‘ruru‘, ‘sun‘, ‘wang‘, ‘yao‘, ‘H‘,‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]

元组

与列表一样,但内容一旦生成,不可修改

NameList=(‘cai’,’ru’,’wang’)

遍历列表

NameList=[‘cai’,’ru’,’wang’]

for name in NameList

Print‘your name is’,name

列表练习程序

  1. 让用户输入工资
  2. 输出购物菜单及产品价格
  3. 计算用户是否可支付
  4. 输出用户剩余的钱,问用户是否可继续购物,如果选择继续,继续进行,直到钱不够为止

补充:

>>> names="cai ru wang"         //定义一变量为字符串

>>> names.split()                //将字符串分成一个列表

[‘cai‘, ‘ru‘, ‘wang‘]

>>> name_list=names.split()

>>> name_list                   //字符串被分成三段

[‘cai‘, ‘ru‘, ‘wang‘]

>>> name_list[1]                //取出ru

‘ru‘

F_choice=choice.strip()      //使choice脱去空格(多余的)

参考程序:

[email protected]:~/python$vim  mai.py

#!/usr/bin/python

import tab

import sys

products = [‘Car‘,‘Iphone‘,‘Coffee‘,‘Mac‘,‘Cloths‘,‘Bicyle‘]

prices  = [250000,4999,    35,     9688, 438,     1500]

shop_list=[]

salary = int(raw_input(‘please input yoursalary:‘))

while True:

print "Things have in the shop.plesae choose one to buy:"

for p in products:

print p,‘\t‘,prices[products.index(p)]

choice = raw_input(‘Please input one item to buy:‘)

F_choice = choice.strip()

if F_choice in products:

product_price_index = products.index(F_choice)

product_price = prices[product_price_index]

print F_choice,product_price

if salary > product_price:

shop_list.append(F_choice)

print "Added %s intoyour shop list" % F_choice

salary = salary -product_price

print "Salaryleft:",salary

else:

if salary < min(prices):

print ‘Sorry,rest ofyour salary cannot buy anything! 88‘

print "you havebought these things: %s" % shop_list

sys.exit()

else:

print "Sorry ,youcannot afford this product,please try other ones!"

程序运行结果:

[email protected]:~/python$python mai.py

please input your salary:1536

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Car

Car 250000

Sorry ,you cannot afford thisproduct,please try other ones!

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Bicyle

Bicyle 1500

Added Bicyle into your shop list

Salary left: 36

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Bicyle

Bicyle 1500

Sorry ,you cannot afford thisproduct,please try other ones!

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Coffee

Coffee 35

Added Coffee into your shop list

Salary left: 1

Things have in the shop.plesae choose oneto buy:

Car    250000

Iphone 4999

Coffee 35

Mac    9688

Cloths 438

Bicyle 1500

Please input one item to buy:Coffee

Coffee 35

Sorry,rest of your salary cannot buyanything! 88

you have bought these things: [‘Bicyle‘,‘Coffee‘]

[email protected]:~/python$

Python字典讲解与练习

python字典

语法:

DicName={

“key1”: “value”,

“key2”: “value 2”

Contacs={

‘wang’: ‘1886’,

‘cai’: ‘1887’,

‘ru’: ‘1888’,

}

将之前写的购物菜单用字典写:

>>> product_dir={‘car‘:250000,‘Iphone‘:4999,‘coffee‘:35,‘Bicycle‘:1500}

>>> product_dir                                      //查看菜单

{‘car‘: 250000, ‘coffee‘: 35, ‘Bicycle‘:1500, ‘Iphone‘: 4999}

>>> product_dir[‘coffee‘]                               //查价格

35

>>> product_dir.keys()                                //查key

[‘car‘, ‘coffee‘, ‘Bicycle‘, ‘Iphone‘]

>>> product_dir.values()                             //查values

[250000, 35, 1500, 4999]

>>> product_dir.items()                                 //查相对应的

[(‘car‘, 250000), (‘coffee‘, 35),(‘Bicycle‘, 1500), (‘Iphone‘, 4999)]

>>> for i in product_dir:                    //打印product_dir

...  print i

...

car

coffee

Bicycle

Iphone

>>> product_dir.items()

[(‘car‘, 250000), (‘coffee‘, 35),(‘Bicycle‘, 1500), (‘Iphone‘, 4999)]

>>> for p,price in  product_dir.items():                        //打印items()

...  print p,price

...

car 250000

coffee 35

Bicycle 1500

Iphone 4999

字典查看、添加、删除、修改

语法:

Contacs={

‘wang’:’1886’,

‘cai’:’1887’;

‘ru’:’1888’}

查看key:          Contacts.key()

查看value:      Contacts.values()

添加新item到字典:   Contacts[‘yao’]=’1889’

删除item:        Contacts.popitem()                //默认删除第一个

>>> product_dir

{‘car‘: 250000, ‘coffee‘: 35, ‘Bicycle‘:1500, ‘Iphone‘: 4999}

>>>product_dir.has_key(‘car‘)                       //判断car是否存在

True

>>> product_dir.popitem()                         //删除第一个

(‘car‘, 250000)

>>> product_dir

{‘coffee‘: 35, ‘Bicycle‘: 1500, ‘Iphone‘:4999}

练习小程序:员工信息表

1.创建公司员工信息表,员工号、姓名、职位、手机

2.提供查找接口,通过员工姓名查询用户信息

参考程序:

[email protected]:~/python$cat contact_list.txt

1 cai  chengxuyuan  1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

[email protected]:~/python$vim contact_dir.py

#!/usr/bin/python

import tab

contact_file = ‘contact_list.txt‘

f = file(contact_file)

contact_dic = {}

for line in f.readlines():

name = line.split()[1]

contact_dic[name] = line

‘‘‘

for n,v in contact_dic.items():

print "%s \t%s" %(n,v),

‘‘‘

while True:

input = raw_input("Please input the staff name:").strip()

if len(input) == 0:continue

if contact_dic.has_key(input):

print "\033[32.1m%s\033[0m" % contact_dic[input]

else:

print ‘Sorry,no staff namefound!‘

程序运行结果:

[email protected]:~/python$python contact_dir.py

Please input the staff name:zhou

Sorry,no staff name found!

Please input the staff name:cai

1 cai  chengxuyuan  1885

Please input the staff name:chao

3 chao gongchengshi  1887

Please input the staff name:yao

4 yao  chengxuyuan  1888

Please input the staff name:ru

2 ru  gongchengshi  1886

Please input the staff name:

Python函数

函数是在程序中将一组用特定的格式包装起,定义一个名称,然后可以在程序的任何地方通过调用此函数名来执行函数里的那组命令

使用函数的好处:

程序可扩展性

减少程序代码

方便程序架构的更改

定义函数

def sayHi():

print“hello,world!”

def sayHi2(name):

print“hello,%s,howare you?” %name

n=’wang’

sayHi2(n)

>>>sayHi(n)

Hello,wang,how are you?

小试牛刀1:

[email protected]:~/python$vim function1.py

#!/usr/bin/env python

def sayHi(n):

print "Hello %s,how are you?" % n

name = ‘wang‘

sayHi(name)

[email protected]:~/python$python function1.py

Hello wang,how are you?

小试牛刀2:

[email protected]:~/python$more contact_list.txt

1  cai  chengxuyuan 1885

2 ru  gongchengshi  1886

3 chao gongchengshi  1887

4 yao  chengxuyuan  1888

将名字取出,一个一个问hello XXX,how are you

参考:

[email protected]:~/python$vim function2.py

#!/usr/bin/python

def sayHi(n):

print "hello %s,how are you?" %n

contact_file =‘contact_list.txt‘

f = file(contact_file)

for line in f.readlines():

name = line.split()[1]

sayHi(name)

程序结果:

[email protected]:~/python$python function2.py

hello cai,how are you?

hello ru,how are you?

hello chao,how are you?

hello yao,how are you?

函数参数

def info(name,age):

print“Name:%s Age:%s” %(name,age)

综合练习:

写一个atm程序,功能要求:

  1. 额度15000
  2. 可以提现,手续费5%
  3. 每月最后一天出账单(每月30天)
  4. 记录每月日常消费流水
  5. 提供还款接口

优化(可选):

1.每月10号为还款日,过期未还,按欠款额5%计息

输出类似:

本期还款总额: XX

交易日       交易摘要    交易金额   计息

XX            XX         XX          XX

补充:Pickle()#、函数默认参数、关键参数可学习一下,写程序可更加便捷

时间: 2024-07-30 11:29:11

python第二天学习笔记的相关文章

python网络爬虫学习笔记

python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章目录 1. 介绍: 2. 从简单语句中开始: 3. 传送数据给服务器 4. HTTP头-描述数据的数据 5. 异常 5.0.1. URLError 5.0.2. HTTPError 5.0.3. 处理异常 5.0.4. info和geturl 6. Opener和Handler 7. Basic Authentication 8. 代理 9. Timeout 设置 10. Cookie 11. Deb

SHELL第二课学习笔记

SHELL第二课学习笔记 A.脚本规范申明信息: #!bin/bash #Date 14:00 2014-1-30 #Author xiaoping #Mail [email protected] #Function: Thsi scrits funcion is .... #version 1.1 ~ B.注意点: a.成对内容一次写出来 {}.[].''.``.""# b.[]中括号两端需要空格 c.流程控制语句一次性写完格式 d.vi多行缩进 按v进入visual状态,选择多行,

Python核心编程第三版第二章学习笔记

第二章 网络编程 1.学习笔记 2.课后习题 答案是按照自己理解和查阅资料来的,不保证正确性.如由错误欢迎指出,谢谢 1. 套接字:A network socket is an endpoint of a connection across a computer network,Sockets are often represented internally as simple integers, which identify which connection to use. 套接字是网络通信的

python数据分析入门学习笔记儿

学习利用python进行数据分析的笔记儿&下星期二内部交流会要讲的内容,一并分享给大家.博主粗心大意,有什么不对的地方欢迎指正~还有许多尚待完善的地方,待我一边学习一边完善~ 前言:各种和数据分析相关python库的介绍(前言1~4摘抄自<利用python进行数据分析>) 1.Numpy: Numpy是python科学计算的基础包,它提供以下功能(不限于此): (1)快速高效的多维数组对象naarray (2)用于对数组执行元素级计算以及直接对数组执行数学运算的函数 (3)用于读写硬盘

Python高级特性——学习笔记

Python中非常有用的高级特性,1行代码能实现的功能,决不写5行代码.请始终牢记,代码越少,开发效率越高. 1.切片slice.L = [1, 2, 3, 4, 5] L[0:3]=[1,2,3]表示,从索引0开始取,直到索引3为止,但不包括索引3.即索引0,1,2,正好是3个元素. 如果第一个索引是0,还可以省略 倒数切片L[-2:]=[4,5]从倒数第二个数 到 最后一个数 L = list(range(100))# 创建一个0-99的数列L L[:10:2]# 前10个数,每两个取一个

&lt;&lt;Python基础教程&gt;&gt;学习笔记之|第01章|基础知识

本学习笔记主要用要记录下学习<<Python基础教程>>过程中的一些Key Point,或自己没怎么搞明白的内容,可能有点杂乱,但比较实用,查找起来也方便. 第01章:基础知识 ------ Jython:      Python的Java实现,运行在JVM中,相对稳定,但落后于Python,当前版本2.5,在TA(Python+Robot)会用到 IronPython:  Python的C#实现,运行在Common Language Runtime,速度比Python要快 >

锋利的jquery第二版学习笔记

jquery系统学习笔记 一.初识:jquery的优势:1.轻量级(压缩后不到30KB)2.强大的选择器(支持css1.css2选择器的全部 css3的大部分 以及一些独创的 加入插件的话还可支持XPath)3.出色的Dom封装(简化原本复杂的操作)4.可靠的事件处理机制(跨浏览器兼容性)5.完善的Ajax操作(一个$.ajax()方法全部搞定)6.不污染顶级变量(只使用了一个名为jQuery的对象 其别名$也可随时让出其控制权 见解决和其它库混用时解决冲突部分)7.出色的浏览器兼容性(优秀的j

《HeadFirst Python》第二章学习笔记

现在,请跟着舍得的脚步,打开<HeadFirst Python>第二章. 一章的内容其实没有多少,多练习几次就能掌握一个大概了! <HeadFirst Python>的第二章设计得很有意思.它直接从制作一个模块入手,顺带讲了模块的导入,传统的书可不会这么搞. 不过书中关于编辑器的观点略显陈旧. 最好的编辑器是什么? 别用书中推荐的Python自带IDLE,在现阶段,请使用Jupyter Notebook来进行各项练习. 等学完这本书后,你可以选择PyCharm/Eric6/Wing

Python之路第二天-----学习笔记

变量名要点: 1.变量名只能包含字母. 数字和下划线. 变量名可以字母或下划线打头, 但不能以数字打头, 例如, 可将变量命名为message_1, 但不能将其命名为1_message. 2.变量名不能包含空格, 但可使用下划线来分隔其中的单词. 3.不要将Python关键字和函数名用作变量名, 即不要使用Python保留用于特殊用途的单词, 如print  . 4.变量名应既简短又具有描述性. 例如, name比n好, student_name比s_n好, name_length比length