在python中制作存钱罐程序

时间:2014-07-17 00:06:31

标签: python

我是Python和编程的初学者,我正在尝试制作一个能够存入或取出便士,镍币,硬币和四分之一的简单存钱罐。如果我输入硬币以便能够继续添加银行中的硬币总数,我就不知道如何循环代码或如何存储数据。我只能这样做它运行并告诉我,如果我添加,例如,100便士,我的银行有100便士。但后来又重置了。我该怎么做呢?我的代码可能很糟糕,但到目前为止,基于我目前对python的了解(添加了空白部分,例如"返回"和pennies_previous,所以任何阅读都可以理解我的思维过程,以及withdrawstep()函数尚未添加):

print "Welcome to the Piggy Bank!"

def depositstep(): 
    deposit = raw_input("What would you like to deposit? (P for pennies, N for nickels, D for dimes, Q for quarters): ").upper() 

    if deposit == 'P':
        pennies_previous = 
        pennies_instance = raw_input("How many pennies would you like to deposit?: ")
        pennies_total = int(pennies_instance) + pennies_previous 
        print "There are %s pennies in your bank"% (pennies_total)
        return execute()

    elif deposit == 'N':
        N = raw_input("How many nickels would you like to deposit?: ")
        return 

    elif deposit == 'D':
        D = raw_input("How many dimes would you like to deposit?: ")
        return 

    elif deposit == 'Q':
        Q = raw_input("How many quarters would you like to deposit?: ")
        return 

    else:
        return "Sorry. Please Type P for pennies, N for nickels, D for dimes, or Q for quarters."

def execute():
    exc = raw_input("Would you like to deposit or withdraw money? (D for deposit, W for withdraw): ").upper()

    if exc == 'D' or exc == 'DEPOSIT':
        return depositstep()                        

    elif exc == 'W' or exc == 'WITHDRAW':
        return withdrawstep()

    else:
        return "Sorry. Please type D for deposit or W for withdrawal." 

print execute()

3 个答案:

答案 0 :(得分:0)

您应该将总金额存储在原始变量中。 pennies_previous = int(pennies_instance)+ pennies_previous然后将存储便士的数量。

答案 1 :(得分:0)

如果您希望银行继续为每个会话存储银行的价值,那么您将要将银行的值保存到文件中。你可以这样做: 1.首先,创建一个名为bankvalue.txt的文件。 2.然后,在每次返回之前添加这些行:

value = open(bankvalue.txt, 'w') # that opens your bankvalue.txt file in write mode
value.write('\n'pennies_previous) #You should use the answer above for the pennies_previous
value.close() #saves the file

3.然后,为了告诉一个人他们的余额你将使用readline()函数

我希望那就是你要找的东西

答案 2 :(得分:0)

我会使用python字典而不是变量:

这样做:

bank = {'pennies':0, 'nickles':1, 'dimes':0, 'quarter':0}

增加你做的那些

bank['pennies'] += int(pennies_instance) # not need the pennies_previous

然后您需要将其写入您可以执行的文件:

f = open('filename','w') 
f.write(bank.items())
f.close

但是这不保留python结构。但您可以使用json module,这很简单:

import json

f = open('filename','wb')
json.dump(bank,f)
f.close()

在脚本开始时,您需要从文件中获取数据,然后使用

执行此操作
f = open('bank.dat','rb')
bank = json.load(f)

看起来像这样:

import json

f = open('bank.dat','rb')
bank = json.load(f)
f.close()

## you code goes here.

f = open('bank.dat','wb')
json.dump(bank,f)
f.close()

您的代码中还有一些其他问题也应该解决。

1)在代码的“else”部分,如果用户输入了错误的字母,它就会终止,而应该再次调用该函数。

2)你不需要返回一个字符串并在'print execute()'中打印它,你可以将它打印到位并且不返回任何内容。