Python电力免单算法开发报错求助:实现最低用电量日识别功能
Fixing Your Free Electricity Day Calculator
Hey there! Let's get that error sorted and make your free electricity day tool work like a charm. First, let's break down why you're seeing the can only concatenate list (not "int") to list message:
- The line
electric[electric + 1] = int(input(...))is the culprit.electricis your list of usage values, and Python won't let you add a list to an integer (1) to get an index. You need to use the loop's index variableiinstead to target the right position in the list.
Here's a revised, working version of your function with clear improvements:
def ElectricSupplier(): # Initialize an empty list to store daily electricity usage (cleaner than pre-filling empty strings) electric = [] # Day labels to make input prompts and output more user-friendly day_labels = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th"] # Loop through each day of the week to collect input for i in range(7): # Get input, convert to integer, and add to the list daily_units = int(input(f"Enter Units Of Electricity Used for {day_labels[i]} day - ")) electric.append(daily_units) # Find the index of the smallest usage value min_usage_index = electric.index(min(electric)) # Output the free day as requested print(f"{day_labels[min_usage_index]} day is the day that you will get free electricity") # Call the function to run the program ElectricSupplier()
Key fixes & enhancements:
- Corrected list handling: Used
append()to add each daily value to the list (no more invalid index math). - Clearer user prompts: Added day labels to the input question so users know which day they're entering data for.
- Simplified min value lookup: Used
min(electric)to get the lowest usage, thenindex()to map it back to the corresponding day.
Bonus: Handling tied minimum usage
If two or more days have the same lowest usage, the code above will pick the first occurrence. If you want to notify the user about all qualifying days, replace the final print section with this:
min_usage = min(electric) free_days = [day_labels[i] for i, usage in enumerate(electric) if usage == min_usage] if len(free_days) == 1: print(f"{free_days[0]} day is the day that you will get free electricity") else: print(f"The days you get free electricity are: {', '.join(free_days)} days")
内容的提问来源于stack exchange,提问作者Jowan Mckend
相关产品推荐
相关产品推荐

