典型代码:
1, 注释
2, 函数调用
3, 带参数的函数返回值
4, 无返回值的 return 语句
5, 字典变量的赋值和使用
6,txt 文件读取
7, 文件变量
8, 异常处理
9, 输出结果
10, 列表排序
11, 字符串分割
12, 空字符处理
13, 判断
14, 循环
这是一个典型案例代码
- def sanitize(time_string): #函数定义及实参传递
- if '-' in time_string: #判断一个字符串中是否存在'-'支付; 判断语句
- splitter = '-'
- elif ':' in time_string: #elif 语句
- splitter = ':'
- else: #else 语句
- return(time_string) #带参数的函数返回语句
- (mins,secs) = time_string.split(splitter) #多个变量的自动赋值, 字符串分割
- return(mins+'.'+secs) #参数计算后的函数返回语句
- def get_coach_data(filename):
- try: #先尝试
- with open(filename) as f: #打开文件
- data = f.readline() #按行读取文件内容并送至变量 data 中
- templ = data.strip().split(',') #取消空字符, 字符串分割
- return({'name':templ.pop(0), #字典变量的赋值,
- 'dob':templ.pop(0),
- 'times':str(sorted(set([sanitize(t) for t in templ]))[0:3])}) #排序, 循环, 取前 3 个字符内容
except IOERROR as ioerr:. #出现异常后的异常处理语句
- print('File error:'+str(ioerr))
- return(None)
- james = get_coach_data('james2.txt') #文件变量
- print(james['name']+"'s fasttest times are"+james['times']) #输出
来源: http://www.bubuko.com/infodetail-2690919.html