Python随机数列表统计功能报错求助:'int'对象无len()方法
Fixing the "object of type 'int' has no len()" Error in Your Random Number List Code
Hey Chris, let's walk through what's causing that error and get your code working properly.
What's Going Wrong?
That error pops up because of a couple of key mistakes in variable initialization and naming:
- You initialized
randomListas an integer (0) instead of an empty list. Integers don't have alen()method, so when you tried to use that later, Python threw an error. - You stored the user's input (the number of random numbers to generate) in a variable named
average—that's not just confusing, it's going to mess up your logic when you actually calculate the average later. - Setting
smallestandlargestto0is also risky. If you generate random negative numbers, those initial values will be wrong.
Here's the Fixed Code
import random def main(): # Get the number of elements from the user, with clear naming num_count = int(input("How many numbers (between 1-100) would you like to generate?: ")) # Make sure the input is within the valid range if num_count < 1 or num_count > 100: print("Whoops, please enter a number between 1 and 100!") return # Initialize an empty list to hold random numbers (not an integer!) random_numbers = [] total = 0 # Generate the random numbers and build the list for _ in range(num_count): current_num = random.randint(0, 100) # Adjust min/max here if needed random_numbers.append(current_num) total += current_num # Calculate all the stats we need average = total / num_count smallest = min(random_numbers) largest = max(random_numbers) # Print out the results nicely print(f"Generated list: {random_numbers}") print(f"Sum: {total}") print(f"Average: {round(average, 2)}") print(f"Smallest number: {smallest}") print(f"Largest number: {largest}") if __name__ == "__main__": main()
Key Changes I Made
- Clear variable names: Renamed things like
average(which held the count) tonum_count, andrandomListtorandom_numbers—this makes the code way easier to read and debug. - Proper list initialization:
random_numbersstarts as an empty list[]instead of0, so you can add elements withappend()and use functions likelen(),min(), andmax()on it without errors. - Input validation: Added a check to make sure the user enters a number between 1 and 100, so your code doesn't behave weirdly with invalid inputs.
- Simplified stats calculation: Used Python's built-in
min()andmax()functions instead of trying to track those values manually—they're reliable and save you code. - Cleaner output: Used f-strings to print results in a readable way, and rounded the average to 2 decimal places for clarity.
Why the < Operator Was Throwing an Error Too
If you tried comparing smallest < randomList before, that was failing because smallest is an integer and randomList was also an integer (you initialized it to 0). Even if you'd tried to compare it to a number later, since randomList wasn't a list of numbers, that comparison didn't make sense. Fixing the list initialization takes care of this problem automatically.
内容的提问来源于stack exchange,提问作者ChrisCrad
相关产品推荐
相关产品推荐

