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
billslist 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.,1becomes"$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
相关产品推荐
相关产品推荐

