如何根据这些说明格式化以下代码? (非编码背景)

时间:2019-05-22 23:40:54

标签: python while-loop menu formatting

我编写了以下代码来显示菜单列表,并允许用户购买商品,但不能超过其礼品卡(250)上的金额。

我在分配作业给我的格式化说明时遇到了麻烦(请参阅下文)。 “在小数点后加8个空格/输入2位数字”是什么意思?您是如何做到的?8.2f和quantity:3d分别代表什么?我迷路了,因为我不是编码人员,而且从未做过格式化。

instead of {prices[i]} add formatting
leave 8 spaces for the number
put 2 digits after a decimal point
f fixed format decimal number
{prices[i]:8.2f}
The print statement (all on one line) looks like:
 print(f"{n} {items[i]:12} {prices[i]:8.2f}")
Cart will show item, price and quantity.
quantity = number_bought[i]
item = items[i]
price = prices[i]
print(f"{quantity:3d} {item:12} {price:8.2f}")
The f string says print the string as is except
parts enclosed in curly braces { }
{quantity}
Python evaluates the variable just after the
opening { and uses that value in the print.
Use a special format convention just after the :
colon.
 3 says "Leave room for 3 digits" (right adjust
them) _ _ _
 d says "integer digits"
 {item:12}
 format after the : colon
  12 says "Leave room for 12 characters
   s (str) string is the default type, and strings fill
 from the left
 so if item is "usb"
  usb followed by 9 spaces for a total of 12
  will print
 Use a special format convention just after the :
 colon.
 3 says "Leave room for 3 digits" (right adjust
 them) _ _ _
 {quantity:3d}
  Use a special format convention just after the :
 colon.
 3 says "Leave room for 3 digits" (right adjust
them) _ _ _
{price:8.2f}
8 spaces for the number including decimal point
.2 2 of our 8 spaces are for decimals
f for "fixed number of decimals in float number"
So printing with an f string means you don't
need to round a number if you specify it like this
Not using f string, print can have rounding
issues
price = 3.01
price = price + 0.01
print(price)
3.0199999999999996
Using f string, print formats numbers nicely
print(f"price each {price:7.2f}")
price each 3.02
for i in range(len(items)):
n = i+1
what = items[i]
cost = prices[i]


gift_card = 250.00
# List of prices
prices = [6.95, 38.72, 18.90, 32.41, 67.44]
# 0 1 2 3 4
# List of item names
 items = ['pen', 'radio', 'usb', 'magazine','printer']
 shopping_cart = [0, 0, 0, 0, 0]
# cart shows number of items bought

def print_lists(items, prices): 
i= 1
while i <= len(items):
    print(i, items[i-1], prices[i-1])
    i= i + 1 
print("0 Exit without choosing any item")
print_lists(items, prices)

choice = int(input("Choose what item you want"))
while choice > 0:
index= choice- 1
shopping_cart[index]= int(input("How many do you want?"))
print(shopping_cart)
gift_card= gift_card-prices[index]*shopping_cart[index]
print(gift_card)
print_lists(items, prices)
choice = int(input("Choose what item you want"))
print(shopping_cart)
print(gift_card)

0 个答案:

没有答案