python 基础之第九天
###############错误和异常########################



说明:e 是错误的具体原因,else 表示没有异常才会执行else的语句,finally 是无乱有没异常都要执行

raise 自定义触发异常
assert 断言异常,assert 后面的为真,这句话没有意义,不会执行;为假,则会执行‘Age out of range’
############例子###############

#############with 语句###################

######################函数的参数####################
#####‘*args'#########
In [9]: def foo(*args):
...: print args
...: In [10]: foo(10)
(10,) In [11]: foo(10,20,'fush')
(10, 20, 'fush') ###########################
In [12]: def add(x,y):
....: return x+y
....:
In [13]: add(*[10,20])
Out[13]: 30
In [14]: add(*(10,20))
Out[14]: 30
###########**args#############
In [15]: def bar(**args):
....: print agrs In [18]: bar(name='bob',age=23)
{'age': 23, 'name': 'bob'}
##########大招################
In [21]: def fun1(args,*non_args,**kwargs):
print args
print non_args
print kwargs In [23]: fun1(10)
10
()
{} In [24]: fun1(10,20)
10
(20,)
{} In [25]: fun1(10,(20,30))
10
((20, 30),)
{} In [26]: fun1(10,(20,30),name='bob')
10
((20, 30),)
{'name': 'bob'}
######################实战案例################

[root@master script]# cat num_game.py
#!/usr/bin/python
# coding:utf-8 import random def probe():
CMDs = {'+':add,'-':sub}
N_list = [random.randint(1,50) for i in range(2)]
N_list.sort(reverse=True)
op = random.choice('+-')
answer = CMDs[op](*N_list)
prompt = '%s %s %s = ' % (N_list[0],op,N_list[1])
tries = 0
while tries < 3:
result = int(raw_input(prompt))
if answer == result:
print 'Very Good!'
break
print 'answer is wrong!'
tries +=1
else:
print '\033[31;1m正确答案是%s%s\033[0m' % (prompt,answer) def add(x,y):
return x+y
def sub(x,y):
return x-y if __name__ == '__main__':
while True:
probe()
choice = raw_input('Contine(Y/N) ').strip()[0]
if choice in 'Nn ':
break
检测:
[root@master script]# python num_game.py
49 + 35 = 45
answer is wrong!
49 + 35 = 45
answer is wrong!
49 + 35 = 45
answer is wrong!
Contine(Y/N) y
27 + 10 = 37
Very Good!
Contine(Y/N) n
#########################记账系统#####################

shell:
[root@master script]# date +%F
2017-08-16
[root@master script]# date +%Y-%m-%d
2017-08-16 python:
In [1]: import time In [2]: time.strftime('%F') #或者 time.strftime('%Y-%m-%d')
Out[2]: '2017-08-16'
代码如下:
[root@master script]# cat account.py
#!/usr/bin/python
# coding:utf-8 import os
import cPickle as P
import time
import sys
def spend_money(wallet,record,date,amount,comment):
with open(wallet) as fobj:
balance = P.load(fobj) - amount
with open(wallet,'w') as fobj:
P.dump(balance,fobj)
with open(record,'a') as fobj:
fobj.write('%-12s%-8s%-10s%-10s%-20s\n' % (date,amount,'N/A',balance,comment)) def save_money((wallet,record,date,amount,comment)):
with open(wallet) as fobj:
balance = P.load(fobj) + amount
with open(wallet,'w') as fobj:
P.dump(balance,fobj)
with open(record,'a') as fobj:
fobj.write('%-12s%-8s%-10s%-10s%-20s\n' % (date,'N/A',amount,balance,comment)) def query_money(wallet,record):
print '%-12s%-8s%-10s%-10s%-20s\n' % ('date','spend','save','balance','comment')
with open(record) as fobj:
for line in fobj:
print line
with open(wallet) as fobj:
print 'New balance:\n%s' %(P.load(fobj)) def show_menu(wallet,record):
CMDs = {'':spend_money,'':save_money,'':query_money}
prompt = """(0) spend_money
(1) save_money
(2) query
(3) quit
Please your choice(0/1/2/3):"""
while True:
try:
choice = raw_input(prompt).strip()[0]
except(KeyboardInterrupt,EOFError):
print "Bye-Bye"
sys.exit(1)
#except IndexError:
# continue
if choice == '':
print 'Bye-Bye'
break
if choice not in '':
print 'Invalid input,Try again'
continue
args = (wallet,record)
if choice in '':
date = time.strftime('%F')
amount = int(raw_input('amount:'))
comment = raw_input('comment:')
args = (wallet,record,date,amount,comment)
CMDs[choice](*args)
if __name__ == '__main__':
wallet = 'wallet.data'
record = 'record.txt'
if not os.path.exists(wallet):
with open(wallet,'w') as fobj:
P.dump(10000,fobj)
if not os.path.exists(record):
os.mknod(record)
show_menu(wallet,record)
效果如下:
[root@master script]# python account.py
(0) spend_money
(1) save_money
(2) query
(3) quit
Please your choice(0/1/2/3):2
date spend save balance comment 2017-08-16 N/A 500 10500 water 2017-08-16 400 N/A 10100 supermarket New balance:
10100
(0) spend_money
(1) save_money
(2) query
(3) quit
Please your choice(0/1/2/3):3
Bye-Bye
python 基础之第九天的更多相关文章
- python基础第一章
Python基础 第一个python程序 变量 程序交互 基本数据类型 格式化输出 基本运算符 流程控制if...else... 流程控制-循环 第一个python程序 文件执行 1.用notepad ...
- 孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9并使用pydocx模块将结果写入word文档
孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9 (完整学习过程屏幕记录视频地址在文末) 今天在上一天的基础上继续完成对我的第一个代码程序的书写. 到今天终于完成了对docx模块针对 ...
- 孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2
孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2 (完整学习过程屏幕记录视频地址在文末) 今天继续学习beautifulsoup对象的属性与方法等内容. 一.今天进一步 ...
- 孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务
孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第五天.今天的感觉是,mongoDB数 ...
- 孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数
孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 不同类型 ...
- 孤荷凌寒自学python第三十九天python 的线程锁Lock
孤荷凌寒自学python第三十九天python的线程锁Lock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 当多个线程同时操作一个文件等需要同时操作某一对象的情况发生时,很有可能发生冲突, ...
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- Python开发【第二篇】:Python基础知识
Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...
- Python小白的发展之路之Python基础(一)
Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...
随机推荐
- 醒醒吧少年,只用Cucumber不能帮助你BDD
转载:http://insights.thoughtworkers.org/bdd/ 引言 在Ruby社区中,测试和BDD一直是被热议的话题,不管是单元测试.集成测试还是功能测试,你总能找到能帮助你的 ...
- C# 线程中更新ListView某单元格导致闪烁问题的解决
项目中需要用线程处理一些事务.处理结果(已经处理的比例)随时显示在ListView的某区域. 由于线程循环动作较快,导致被更新的单元格甚至所在行都有闪烁现象. 后来考虑到线程算的值整数部分未必变化很快 ...
- vue2.0 自定义过滤器
2.0中已经废弃了过滤器,需要我们自定义 <div id="app"> {{message|uppercase}} </div> //过滤器 Vue.fil ...
- OS: 读者写者问题(写者优先+LINUX+多线程+互斥量+代码)(转)
一. 引子 最近想自己写个简单的 WEB SERVER ,为了先练练手,熟悉下在LINUX系统使用基本的进程.线程.互斥等,就拿以前学过的 OS 问题开开刀啦.记得当年学读者写者问题,尤其是写者优先的 ...
- navicat for mysql 快捷键(原创)
navicat for mysql 快捷键(原创) 在谷歌,百度上基本搜索不出来这方面的内容,我总结了一下,方便新手,节省一些探索的时间. 1.ctrl+q 打开查询窗口2.ctr ...
- inch mil mm换算
inch:英寸 mil:密耳 mm:毫米 1mil=0.0254mm=25.4um 1mm=39.37mil 1inch=1000mil=25.4mm
- WPF02(concept)
(转自http://www.cnblogs.com/huangxincheng/archive/2012/06/17/2552322.html)这些天从项目上接触到了wpf,感觉有必要做一个笔记,首篇 ...
- Canvas学习笔记——动画中摩擦力的运用
摩擦力是与物体运动方向相反的力.我们在处理物体运动时,常把物体分解水平(X轴)方向和竖直(Y轴)方向的运动(比如平抛运动),但在处理摩擦力时,如果把摩擦力分解为X轴和Y轴上的阻力,就会出现某条轴上速度 ...
- 如何学习Java?
一点感悟 java作为一门编程语言,在各类编程语言中作为弄潮儿始终排在前三的位置,这充分肯定了java语言的魅力,在实际项目应用中,我们已经无法脱离javaa(Ps当然你可以选择不使用),但它的高性能 ...
- 最新wap手机agent
名称 agent 铃声格式 和弦数 数据量 删除 LGE-CU8080 LGE-CU8080/1.0 UP.Browser/4.1.26l UP.Link/5.1.2.9 pmd2.0 40 ...