Skip to main content
 首页 » 编程设计

Python:在循环中对变量执行用户定义的加法

2025年05月04日14jackei

这是我正在开发的大型“自动售货机”中的一个模块。不过,我遇到了一些问题。如果他们支付的金额不够($1.75),他们将被要求输入额外的金额。我的部分问题是我不知道我应该做什么操作来改变循环内的赤字。我尝试过的所有事情都导致了错误,例如“预计输入最多 1 个参数,得到 3 个”等等。

selection = 5 
loopCount = 0 
deposit = 0 
cost = 1.75 
print("It costs $",cost,".") 
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n")) 
deficit = cost - deposit 
change = deposit - cost 
if deposit < cost: 
    while deficit > 0 and loopCount < 1: 
        ??? = float(input("Please enter an additional $",deficit,".")) 
        loopCount += 1 
if deposit >= cost: 
    print("Thank you for purchasing item#",selection,". Your change is $",change,".") 

请您参考如下方法:

这对我有用。请确保增加 loopCount,因为现在它不会循环多次。

selection = 5 
loopCount = 0 
deposit = 0 
cost = 1.75 
print("It costs $",cost,".") 
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n")) 
deficit = cost - deposit 
change = deposit - cost 
if deposit < cost: 
    while deficit > 0 and loopCount < 1: 
        deficit -= float(input("Please enter an additional ${}.".format(deficit))) 
        loopCount += 1 
if deposit >= cost: 
    print("Thank you for purchasing item#",selection,". Your change is $",change,".")