范围问题,raw_input变量不会重置

时间:2014-07-18 01:50:29

标签: python

我不知道如何更改代码,因此存档变量将在脚本运行时重置,因为如果我先输入便士,则存储变量将在每次调用函数时存储,因此按下不同的像镍一样的硬币它不会执行它的“elif”声明而是转到便士。我该如何解决这个问题?

pennies_total = 0
nickels_total = 0
dimes_toal = 0
quarters_total = 0
keeprunning = True


def deposit():
    global pennies_total
    global nickels_total
    global dimes_total
    global quarters_total
    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' or 'PENNIES':
        pennies_instance = raw_input("How many pennies would you like to deposit?: ")
        pennies_total = int(pennies_instance) + pennies_total
        print "There are %s pennies in your bank"% (pennies_total)

    elif deposit == 'N' or 'NICKELS':    
        nickels_instance = raw_input("How many nickels would you like to deposit?: ")
        # create if non-integer is input for all classes of coins
        nickels_total = int(nickels_instance) + nickels_total
        print "There are %s nickels in your bank"% (nickels_total)

    while keeprunning == True:
        exc = raw_input("Would you like to deposit or withdraw money? (D for deposit, W   for    withdraw, Q for Quit): ").upper()
        if exc == "D" or "DEPOSIT":
            deposit()

2 个答案:

答案 0 :(得分:1)

以下表达式:

deposit == 'P' or 'PENNIES'

不符合您的想法。无论deposit的值如何,该表达式始终都为真。因此,总是采用便士分支,从不采取镍分支。

尝试:

deposit == 'P' or deposit == 'PENNIES'

deposit in ('P', 'PENNIES')

和其他if语句类似。

答案 1 :(得分:0)

两个变化:

1)在:

中更改变量名称
deposit = (raw_input("What would you like to deposit? (P for pennies, N for nickels, D for dimes, Q for quarters): ")).upper()

以及其他名称:denomination

2)替换:

if deposit == 'P' or 'PENNIES':

人:

if (denomination == 'P') or (denomination == 'PENNIES'):

对"所有"进行此更改如果和" elif"条件。