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

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 randomList as an integer (0) instead of an empty list. Integers don't have a len() 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 smallest and largest to 0 is 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) to num_count, and randomList to random_numbers—this makes the code way easier to read and debug.
  • Proper list initialization: random_numbers starts as an empty list [] instead of 0, so you can add elements with append() and use functions like len(), min(), and max() 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() and max() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:01:12