zoukankan      html  css  js  c++  java
  • 【Python第31课到42课】

    【Python第31课到42课】 【31】读文件 f=file('data.txt') data=f.read() print data f.close 其他用法 data.txt中存的内容是 hi my name is mike helloworld! 当运行 f=file('data.txt') data=f.readlines() #把内容按行读取至一个list中 ,所有内容都读出来了。 print data f.close 结果 ['hi my name is mike ', 'helloworld!'] 当运行 f=file('data.txt') data=f.readline() #把内容读取一行出来 print data f.close 结果 hi my name is mike 【32】写文件 打开文件有file()和open()两种方法 用法一致 write示例 data='I will be in a file . So cool' out = open ('output.txt','w') out.write(data) out.close() appending示例 data=' add new data' out = open ('output.txt','a') out.write(data) out.close() 【33】处理文件中的数据 统计总分 KK 23 34 23 JJ 40 40 40 23 zz 99 99 11 11 GG 100 程序: f=file('data.txt') lines=f.readlines() #print lines f.close() results=[] for line in lines: #print line data=line.split() #print data sum=0 for score in data[1:]: sum+=int(score) result='%s :%d ' %(data[0],sum) #print result results.append(result) #print results output=file('result.txt','w') output.writelines(results) output.close() 结果: KK :80 JJ :143 zz :220 GG :100 【34】break 例子1: while True: a=raw_input() if a=='EOF': break 【35】continue 类上 【36】异常处理 try...except 例子1: try: f=file('none-exist.txt') print 'file opened' f.close() except: print 'File not exist' print 'Done' 【37】字典 字典dictionary,基本格式(key健,value值) 注意 1.健必须唯一 例子1: score ={ 'kk':99, 'zz':100, 'll':59 } print score['kk'] 输出结果: 99 用for...in遍历 score ={ 'kk':99, 'zz':100, 'll':59 } for name in score: print score[name] 结果: 99 59 100 注意,这里的输出结果的顺序和score定义的顺序不一样了。 2.改 score['kk']=18 3.增 score['aa']=88 4.删 del score['kk'] 5.空字典 score={} 【38】模块 from 模块名 import 方法名 例子1: from random import randint num = randint(1,10) print num 例子2: import random num=random.randint(1,10) print num 例子3: 查看random有哪些函数和变量 dir(random) 例子4: from math import pi print pi 例子5: 给引入的方法换个名字 from math import pi as math_pi print math_pi 【39-41】用文件保存游戏 【42】函数的默认参数 程序1: def hello (name ='world'): print 'hello'+name hello() hello('python') 结果: helloworld hellopython 程序2: def addfun(a,b=5):#def addfun(a=5,b=3)是错误的用法。默认参数必须在参数表的末尾 return a+b c=addfun(3) print c 结果: 8
  • 相关阅读:
    关于方差所引发的遐想
    POJ 1390 Blocks
    POJ 1722 SUBTRACT
    BZOJ 1901 Dynamic Rankings
    关于Shine-hale
    ACM恢复训练(一)最短路
    CSP退役记
    校内模拟赛(三)(9.24)
    校内模拟赛(二)(9.12)
    校内模拟赛(一)(2019.9.10)
  • 原文地址:https://www.cnblogs.com/2012begin/p/3641091.html
Copyright © 2011-2022 走看看