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

Python自定义throw函数无返回值问题求助

Fixing Your Python Dice Throw Function for Your Drinking Game

Hey there! Let's get that dice-throwing function working so you can finish building your drinking game with friends—sounds like a fun project! 😊

First, let's walk through the issues in your code:

  • You forgot to import the random module: Python has no idea what random.randint() is unless you tell it to load the random module first. That's a quick fix.
  • You're passing an argument to a function that doesn't accept any: Your throw() function is defined without parameters, but you're calling it as throw(List)—that'll trigger a TypeError immediately.
  • The loop logic is off: Your while loop condition was causing the function to generate more than 6 dice rolls (it would make 7, actually!). The way you were tracking iterations with i plus checking the list length was creating a mismatch.

Here's a clean, fixed version of your code using a Pythonic list comprehension (it's shorter and easier to read):

import random

def throw():
    # We want 6 dice rolls, so generate a list of 6 random integers between 1-6
    return [random.randint(1, 6) for _ in range(6)]

# Call the function (no arguments needed!) and print the result
print(throw())

If you'd rather stick with a while loop approach (maybe you're practicing loops specifically), here's the corrected loop version:

import random

def throw():
    dice_count = 6
    roll_list = []
    # Keep adding rolls until we have exactly 6
    while len(roll_list) < dice_count:
        roll_list.append(random.randint(1, 6))
    return roll_list

print(throw())

A quick note: I renamed your variable List to roll_list because using capitalized names like that can clash with Python's built-in types (like list()) and it's not standard practice—small things that make your code easier to maintain later!

内容的提问来源于stack exchange,提问作者Bram van de Poll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:27:37