###############错误和异常########################

说明: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 基础之第九天的更多相关文章

  1. python基础第一章

    Python基础 第一个python程序 变量 程序交互 基本数据类型 格式化输出 基本运算符 流程控制if...else... 流程控制-循环 第一个python程序 文件执行 1.用notepad ...

  2. 孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9并使用pydocx模块将结果写入word文档

    孤荷凌寒自学python第七十九天开始写Python的第一个爬虫9 (完整学习过程屏幕记录视频地址在文末) 今天在上一天的基础上继续完成对我的第一个代码程序的书写. 到今天终于完成了对docx模块针对 ...

  3. 孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2

    孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2 (完整学习过程屏幕记录视频地址在文末) 今天继续学习beautifulsoup对象的属性与方法等内容. 一.今天进一步 ...

  4. 孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务

    孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第五天.今天的感觉是,mongoDB数 ...

  5. 孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数

    孤荷凌寒自学python第四十九天继续研究跨不同类型数据库的通用数据表操作函数 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天继续建构自感觉用起来顺手些的自定义模块和类的代码. 不同类型 ...

  6. 孤荷凌寒自学python第三十九天python 的线程锁Lock

    孤荷凌寒自学python第三十九天python的线程锁Lock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 当多个线程同时操作一个文件等需要同时操作某一对象的情况发生时,很有可能发生冲突, ...

  7. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  8. Python开发【第二篇】:Python基础知识

    Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...

  9. Python小白的发展之路之Python基础(一)

    Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...

随机推荐

  1. U盘启动时提示starting cmain,3种终极解决方案

    U盘启动时提示“starting cmain”一般是这样子的: <ignore_js_op> 这种情况,一般是制作好了PE启动U盘之后,启动不了才会这样,一般正常情况的话,这一句英文是一闪 ...

  2. 怎样高速启动Android模拟器(Android Emulator)

    总所周知,每次我们启动Android Emulator,都须要花费非常长一段时间,几分钟甚至十几分钟.事实上,我们能够使用快照(Snapshot)功能,来高速启动Android模拟器. 首先.须要在A ...

  3. 初涉IPC,了解AIDL的工作原理及用法

    初涉IPC,了解AIDL的工作原理及用法 今天来讲讲AIDL.这个神奇的AIDL,也是近期在学习的,看了某课大神的解说写下的blog,希望结合自己的看法给各位同价通俗易懂的解说 官方文档:http:/ ...

  4. 控制显示input隐藏和查看密码

    通过更改input的password和text类型即可实现 //点击函数,获取dom,判断更改属性. show(){ let input=document.getElementById("i ...

  5. odoo 有哪些文档资源

    // openbook [覆盖 openerp 7 及之前版本] https://doc.odoo.com/     // 最新的 odoo documentation user[覆盖 odoo 9] ...

  6. Adam:大规模分布式机器学习框架

    引子 转载请注明:http://blog.csdn.net/stdcoutzyx/article/details/46676515 又是好久没写博客,记得有一次看Ng大神的訪谈录,假设每周读三篇论文, ...

  7. YAML 对中文的处理

    from yaml import load,dump f = open('xx.ymal',encoding='utf-8') l = load(f) print(f) w = open('xx_co ...

  8. Nginx详细的安装教程(linux)

    转:https://blog.csdn.net/u013641234/article/details/73838472 Nginx作为一个web服务器,目前使用最多的就利用其负载均衡,本篇着重讲解的是 ...

  9. Python list 和 str 互转

    一.list转字符串 命令:''.join(list)其中,引号中是字符之间的分割符,如“,”,“;”,“\t”等等如:list = [1, 2, 3, 4, 5]''.join(list) 结果即为 ...

  10. 构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统(62)-EF链接串加密

    前言: 这一节提供一个简单的功能,这个功能看似简单,找了一下没找到EF链接数据库串的加密帮助文档,只能自己写了,这样也更加符合自己的加密要求 有时候我们发布程序为了避免程序外的SQL链接串明文暴露,需 ...