You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将循环输入的数值存入数组并格式化为指定货币格式输出?

Hey there! Let's get your code to output those bills in the formatted list you want. Here's how to adjust it step by step:

First, your original code only tracks the total sum but doesn't save each individual bill amount—so we need a list to store those values first. Then we can format each one and assemble the final output string.

Here's the modified code:

total_sum = 0
counter = 1
bills = []  # Create a list to store each input bill value

for _ in range(6):
    # Use an f-string for cleaner input prompt formatting
    bill_amount = float(input(f'Enter Bill #{counter}: '))
    bills.append(bill_amount)  # Add the input to our list
    total_sum += bill_amount
    counter += 1

# Format each bill to have a $ prefix
formatted_bill_strings = [f"${amount}" for amount in bills]

# Assemble and print the final formatted list
print(f"[{', '.join(formatted_bill_strings)}]")

What changed:

  • Added a bills list to keep track of every input value (since we need to reference them later for formatting).
  • Switched to f-strings for both the input prompt and formatting the dollar amounts—they're more readable and concise than string concatenation with str().
  • Used a list comprehension to convert each numeric bill amount into a string with a $ prefix (e.g., 1 becomes "$1").
  • Used ', '.join(...) to combine all formatted strings into a single comma-separated string, then wrapped it in square brackets for the final output.

When you input 1,2,3,4,5,6, this will print exactly: [$1, $2, $3, $4, $5, $6]

内容的提问来源于stack exchange,提问作者wRONGx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:32:41