2014-03-30 20 views
0
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 

我基本上想要「改變」的價值。Python:while循環/控制語句沒有達到想要的結果,我該如何解決這個問題?

以上是錯誤的,因爲它不是'存儲'第一次付款的價值,如果它低於成本,意識到我的壞錯誤。

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) 
+0

從環 –

+0

不取出'change'幫幫我 :( – user3451660

回答

0

循環條件說:

while payment< cost: 

所以,當支付比成本更環路會自動存在。因此,一個更簡單的方法將是,

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

表兄弟姐妹,當循環結束時,我們知道,支付應> =成本...

相關問題