Python:虽然循环/控制语句没有达到预期的结果,我该如何解决这个问题?

时间:2014-03-30 11:33:40

标签: loops if-statement for-loop python-3.x while-loop

cost = int(input("Enter the cost:\n"))
payment = int(input("Deposit a coin or note:\n"))

if payment >= cost:
    change = payment - cost
    print (change)

elif payment < cost:
    while payment < cost:
        payment = int(input("Deposit a coin or note:\n"))
        change = cost - payment
        print (change)
        break

我基本上想要“改变”的价值。

以上是错误的,因为它没有“存储”第一笔付款的价值,如果它低于成本,意识到我的错误。

cost = int(input("Enter the cost:\n"))
payment = 0
while payment < cost:
    firstpayment = int(input("Deposit a coin or note:\n"))
    payment = payment + firstpayment
    if payment > cost:
        change = payment - cost
        print ("Your change is: $",change)

1 个答案:

答案 0 :(得分:0)

循环条件说:

while payment< cost:

因此,当付款超过成本时,循环自动存在。因此,更简单的方法是,

while payment<cost:
    #do something
change = payment-cost

因为,当循环结束时,我们知道付款应该是&gt; =费用......