Python自定义throw函数无返回值问题求助
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
randommodule: Python has no idea whatrandom.randint()is unless you tell it to load therandommodule 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 asthrow(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
iplus 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

