你可以在程序最后加一行getchar()表示从键盘输入一个字符。这样程序在输出结果之后,就会等待键盘输入,你就可以观看运行结果。若要退出程序,按回车键即可。如果在getchar()之前输出一行"PressEntertoexit"之类的提示信息会更人性化。
你也可以在控制台(cmd)中,输出该exe文件的文件名以执行之。执行结束后,控制台不会退出,从而你也可以看到结果。
首先检查一下这个程序以前是不是运行过?有没有关闭的运行窗口?请把它们全部关闭以后再重新编译。也可以把这个程序窗口整个关闭后再重新打开编译程序和需要编译的源代码。另外,从粘贴的代码来看,当中的花括号配对好像有点问题。import pickle
import time
import os
def cost(fname):
'用于记录花费'
cost_time = time.strftime('%Y-%m-%d')
try:#异常处理机制
cost_deposit = int(input('花销金额:'))
cost_mark = input('花销说明:')
except ValueError:
print('无效的金额')
return # 函数的return类似于循环的break,return提前结束函数。
except (KeyboardInterrupt, EOFError):
print('\nbye-bye')
exit(1)
# 在文件中取出所有的收支记录
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
# 计算最新余额
balance = records[-1][-2] - cost_deposit
# 构建最新一笔收入
record = [cost_time,0,cost_deposit,balance,cost_mark]
# 将收入追加到收支列表中
records.append(record)
# 将最新收支情况写入文件
with open(fname,'wb') as fobj:
pickle.dump(records,fobj)
def save(fname):
save_time = time.strftime('%Y-%m-%d')
try:
save_deposit = int(input('收入金额:'))
save_mark = input('收入说明:')
except ValueError:
print('无效的金额')
return
except (KeyboardInterrupt,EOFError):
print('bye-bye')
exit(1)
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] + save_deposit
record = [save_time,save_deposit,0,balance, save_mark]
records.append(record)
with open(fname, 'wb') as fobj:
pickle.dump(records, fobj)
def query(fname):
'用于查账'
# 打印表头
print(f'{"date":<15}{"save":<8}{"cost":<8}{"balance":<12}{"mark":<50}')
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
for date,cost,save,balance,mark in records:
print(f'{date:<15}{cost:<8}{save:<8}{balance:<12}{mark:<50}')
def menu():
funcs = {'0':cost,'1':save,'2':query}
prompt = '''(0)开销
(1)收入
(2)查询
(3)退出
请选择(0/1/2/3):'''
fname = 'account.data'
if not os.path.exists(fname):
init_data = [[time.strftime('%Y-%m-%d'),0,0,10000,'init_data']]
with open(fname,'wb') as fobj:
pickle.dump(init_data,fobj)
while 1:
try:
choice = input(prompt).strip()
except(KeyboardInterrupt,EOFError):
choice = '3'
if choice not in ['0','1','2','3']:
print('无效输入,重试')
continue
if choice == '3':
print('\nbye_bye')
break
funcs[choice](fname)
if __name__ == '__main__':
menu()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)