在python中:如何在每次在for循环中运行时将用户从列表中接收的int分开,我需要在下一轮之前划分我从该轮中收到的值?
这是我的代码:
a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
for i in coin_bills:
hef = b - a
print (hef / i), '*', i
else:
print 'pay up!'
示例:a=370 b=500 ---> b-a=130
现在在循环中我将收到(当i = 100时)1,并且(当i = 50时)我将收到2但我希望在第二轮(当i = 50时)除以30(130[=b-a]- 100[=answer of round 1*i]
) 50.
我需要在代码中更改什么?
谢谢!
答案 0 :(得分:2)
您只需从您返回的总变化金额中减去每一步所提供的变更金额。如果将变量名称更改为有意义的名称,则更容易看出:
price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
您还可以通过仅打印实际返回的硬币/钞票来清理输出。然后内循环看起来像这样:
for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
答案 1 :(得分:0)
好的,我假设您正在尝试使用多种类型的账单来计算交易的变化。
问题是你需要保持一个运行记录,告诉你还有多少变化。我使用num_curr_bill
来计算您支付的当前帐单类型的数量,并将hef
我更改为remaining_change
(这对我来说意味着什么)支付。
a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]
if b>=a:
# Calculate total change to pay out, ONCE (so not in the loop)
remaining_change = b-a
for i in coin_bills:
# Find the number of the current bill to pay out
num_curr_bill = remaining_change/i
# Subtract how much you paid out with the current bill from the remaining change
remaining_change -= num_curr_bill * i
# Print the result for the current bill.
print num_curr_bill,'*',i
else:
print 'pay up!'
因此,对于120的价格和现金支付175,输出是:
price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5
一个50和一个5的账单加起来55,正确的变化。
编辑:我会更谨慎地使用我自己的代码中的注释,但我在这里添加了它们以供解释,以便您可以更清楚地了解我的思维过程。
编辑2:我会考虑删除coin_bills中的0.5并用1.0替换1,因为无论如何,任何小数量的数据都将为0.5的分数。