如何在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
0to 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 afloat(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_priceis a shorthand fortotal_price = total_price + current_price—it's cleaner and more readable for updating running totals.- The
:.2fin 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
相关产品推荐
相关产品推荐

