【问题标题】:Display a list of items without using a list在不使用列表的情况下显示项目列表
【发布时间】:2022-01-26 18:53:06
【问题描述】:

我正在尝试创建一个程序,该程序输入价格和税率,并以有序的格式返回商品编号、价格、税率和商品价格。 以下是标准:

  • 用户可以输入多个项目,直到用户另有说明。
  • 它计算并在底部显示购买物品的总金额。
  • 总金额1000以上可享受3折优惠

我不允许使用数组来解决这个问题,我必须在屏幕上将输入与输出分开。

此处显示示例输出:

Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n) y
Enter the price: 34
Enter the tax rate: 10
Are there any more items? (y/n) y
Enter the price: 105.45
Enter the tax rate: 7
Are there any more items? (y/n) n


Item  Price  Tax Rate %  Item Price
====================================
1     245.78        12%      275.27
2     34.00         10%      37.40
3     105.45        7%       112.83

Total amount: $425.51

到目前为止,这是我的代码:

price= float(input('Enter the price: '))
taxRate= float(input('Enter the tax rate: '))
itemPrice = price * (1 + taxRate/100)
acc= 0
while True:
  query=input('Are there any more items? (y/n)')
  if query== 'y':
    price= float(input('Enter the price: '))
    taxRate= float(input('Enter the tax rate: '))
    itemPrice = price * (1 + taxRate/100)
    print(itemPrice )
    acc+=1
  elif query=='n':
    break
print ("Item     Price    Tax Rate%    Item Price")
print ("=========================================")
print( (acc+1) , format(price,'10.2f'), format(taxRate,'10.2f') ,
      format(itemPrice,'14.2f') )

for num in range(0,acc):
  print (acc, price, taxRate, itemPrice)

输出如下所示:


Enter the price: 245.78
Enter the tax rate: 12
Are there any more items? (y/n)y
Enter the price: 34
Enter the tax rate: 10
37.400000000000006
Are there any more items? (y/n)y
Enter the price: 105.45
Enter the tax rate: 7
112.8315
Are there any more items? (y/n)n
Item     Price    Tax Rate%    Item Price
=========================================
3     105.45       7.00         112.83
2 105.45 7.0 112.8315
2 105.45 7.0 112.8315

我只是很难在不使用数组的情况下尝试做到这一点.. 谁能提供帮助?

【问题讨论】:

  • 是否允许dicts?
  • 如果没有某种数据结构,这似乎是不可能的
  • 也不允许使用字典
  • 税率总是整数吗?没有小数显示?您在代码中执行此操作,但在顶部的示例中,没有显示小数。

标签: python algorithm for-loop math while-loop


【解决方案1】:

你可以建立一个字符串作为输出的缓冲区吗?

像这样:

out = ""
acc = 0
totalAmount = 0
query = 'y'
while query == 'y':
    price = float(input('Enter the price: '))
    taxRate = float(input('Enter the tax rate: '))
    itemPrice = price * (1 + taxRate/100)
    acc += 1
    totalAmount += itemPrice
    out += f"{acc:>4} {price:9.2f} {taxRate:11.2f}% {itemPrice:13.2f}\n"
    query = input('Are there any more items? (y/n) ')

print("Item     Price    Tax Rate%    Item Price")
print("=========================================")
print(out)
print(f"Total amount: ${totalAmount:.2f}")

if totalAmount >= 1000:
    print("    Discount: 3%")
    print(f"Total amount: ${totalAmount*0.97:.2f} (after discount)")

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 2022-11-13
  • 2020-09-29
  • 1970-01-01
相关资源
最近更新 更多