这是用户输入处理0的最佳方法吗?

时间:2018-06-12 14:05:55

标签: python list loops divide-by-zero

我正在为我的公司编写一个程序,需要进行一些划分。对于其中一个用户输入,0可能是变量,但是需要对其进行划分。如果opps == 0,则salesaddon无关紧要,但总数可能仍会由用户分配给它。第9行包含我的解决方案,但它需要输入错误信息。有没有更好的方法来解决这个问题?

ans = 'y'

opps = []
sales = []
addon = []
total = []

while ans in ['y', 'Y', 'yes', 'Yes', 'YES']:
    opps.append(int(input("Number of opportunities: ")))
    while opps[-1] == 0:
        opps.append(int(input("Number of opportunities can not equal 0, input at least 1: ")))
    sales.append(int(input("Quantity of of sales: ")))
    addon.append(float(input("Addon $ amount: ")))
    total.append(float(input("Sales dollar amount: ")))

cra =  (sales[-1] / opps[-1]) * 100
addonp = (addon[-1] / total[-1]) * 100

print("\nResults: " + "\nAddon %: " + "%.2f" % addonp + "%\n" "CRA %: " + "%.2f" % cra + "%\n")

ans = str(input("Continue? (Y/N)"))

if ans not in ['y', 'Y', 'yes', 'Yes', 'YES']:

    oppst = sum(opps)
    salest = sum(sales)
    addont = sum(addon)
    cratp = (salest / oppst) * 100
    tsales = sum(total)
    addontp = (addont / tsales) * 100

    print("\nYour totals are: \n" + 
    "\n" +
    "Opportunities: " + str(int(oppst)) + "\n" +
    "\n" +
    "# of Sales: " + str(int(salest)) + "\n" +
    "\n" +
    "Addon $ amount: " + "$" + "%.2f" % addont + "\n" +
    "\n" +
    "Addon %: " + "%.2f" % addontp + "%\n" +
    "\n" +
    "CRA %: " +  "%.2f" % cratp + "%\n" +
    "\n" +
    "Total Sales: " + "$" + "%.2f" % tsales
            )

input("\nPress any key to close...")

0 个答案:

没有答案