将总金额转换为单独的账单Python

时间:2018-10-11 01:50:44

标签: python python-3.x

因此,我尝试输入一个数据,将其转换为USD,然后告诉我它有多少张单独的帐单。我有

def read_exchange_rates():
    answer={}
    answer['USD'] = 1
    answer['GBP'] = 0.76
    return answer
class Money:

    exchange_rates = read_exchange_rates()

    def __init__ (self, monamount, code):
        self.monamount=monamount
        self.code=code
    def to(self, othercode):
        i = self.monamount/self.exchange_rates[self.code]
        j = i*self.exchange_rates[othercode]
        return j
    def __str__(self):
        return str(self.code)+' '+str(self.monamount)
    def bills(self):
        j=self.to('USD')
        hundred=j//100
        return hundred
        jwohundred=j-100*hundred
        return jwohundred
        fifty=jwohundred//50
        return fifty
        jwofifty=jwohundred-fifty*50
        return jwofifty
        twenty=jwofifty//20
        return twenty
        jwotwenty=jwofifty-twenty*20
        ten=jwotwenty//10
        return ten
        jwoten=jwotwenty-ten*10
        return jwoten
        five=jwoten//5
        return five
        jwofive=jwoten-five*5
        return jwofive
        one=jwofive//1
        return one
        jwoone/jwofive-one*1
        return jwooone
        print('The bills/noted for USD'+' '+str(j)+' are:')
        print('USD 100 = '+str(jwohundred))
        print('USD 50 = '+str(jwofifty))
        print('USD 20 = '+str(jwotwenty))
        print('USD 10 = '+str(jwoten))
        print('USD 5 = '+str(jwofive))
        print('USD 1 = '+str(jwoone)) 

如果我先执行a = Money(145.1,'GBP')然后执行a.bills(),则返回的全部是1.0。它应该返回

The bills for USD 220.08 are:
USD 100 = 2 
USD 50 = 0
USD 20 = 1
USD 10 = 0
USD 5 = 0
USD 1 = 0

我做错了什么?我知道有一种使用字典的方法,但我不知道如何使用。谢谢。

2 个答案:

答案 0 :(得分:3)

如果打算在bill函数内部输出结果,则不要在完成打印之前让它返回。最后,您可以返回所有票据数量的元组。另外,您想要的值是hundredfifty等,而不是jwohundredjwofifty等:

def bills(self):
    j = self.to('USD')
    hundred = j // 100
    jwohundred = j - 100 * hundred
    fifty = jwohundred // 50
    jwofifty = jwohundred - fifty * 50
    twenty = jwofifty // 20
    jwotwenty = jwofifty - twenty * 20
    ten = jwotwenty // 10
    jwoten = jwotwenty - ten * 10
    five = jwoten // 5
    jwofive = jwoten - five * 5
    one = jwofive // 1
    jwoone / jwofive - one * 1
    print('The bills/noted for USD' + ' ' + str(j) + ' are:')
    print('USD 100 = ' + str(hundred))
    print('USD 50 = ' + str(fifty))
    print('USD 20 = ' + str(twenty))
    print('USD 10 = ' + str(ten))
    print('USD 5 = ' + str(five))
    print('USD 1 = ' + str(one))
    return hundred, fifty, twenty, ten, five, one

答案 1 :(得分:2)

当函数返回它的返回值时,它就完成了执行。这里仅执行第一条语句。

如果您唯一关心的是结尾处的print语句,请摆脱return语句。如果您需要退货,则可以在最后一条语句中将它们一起退回:

return jwohundred, jwofifty, jwotwenty, jwoten, jwofive, jwoone