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 = {'0':spend_money,'1':save_money,'2':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 == '3':
            print 'Bye-Bye'
            break
        if choice not in '0123':
            print 'Invalid input,Try again'
            continue
        args = (wallet,record)
        if choice in '01':
            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

 

posted @ 2017-08-16 09:47  大漠之烟  阅读(176)  评论(0编辑  收藏  举报