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

如何在for循环中对用户输入数值求和?含7次价格输入练习

How to Sum 7 User-Input Prices in a Python For Loop

Hey there! Let's get your code working to collect 7 prices and calculate their total sum. You're already on the right track with the for loop—we just need to add a few key pieces to make it handle the summation properly.

Step-by-Step Fix & Explanation

  • Initialize a total variable: Start with a variable set to 0 to keep track of the running total. This gives us a starting point to add each price to.
  • Convert input to a numeric type: The input() function returns a string by default, so we need to convert it to a float (since prices often have decimals) before we can do math with it.
  • Update the total in each loop: Every time we get a valid price from the user, add it to our total variable.

Complete Basic Code

# Start with a total of 0
total_price = 0

# Run the loop exactly 7 times
for _ in range(7):
    # Get input, convert to float, and add to the total
    current_price = float(input("What is the price? "))
    total_price += current_price

# Print the final total (formatted for currency)
print(f"Total sum of all prices: ${total_price:.2f}")

Key Details to Note

  • We use _ as the loop variable because we don't need to reference the iteration number—it's a standard Python convention for variables we don't intend to use.
  • total_price += current_price is a shorthand for total_price = total_price + current_price—it's cleaner and more readable for updating running totals.
  • The :.2f in the print statement formats the total to 2 decimal places, which makes sense for displaying currency values.

Bonus: Make It Robust Against Invalid Inputs

If you want to prevent the program from crashing if someone enters a non-number (like a word), add a try-except block to validate input:

total_price = 0

for _ in range(7):
    while True:
        try:
            current_price = float(input("What is the price? "))
            break  # Exit the loop once valid input is received
        except ValueError:
            print("Oops! Please enter a valid number (e.g., 15.99).")
    total_price += current_price

print(f"Total sum of all prices: ${total_price:.2f}")

This will keep prompting the user until they enter a valid number, so your program won't break unexpectedly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:14:44