如何仅打印最终列表结果而非所有中间列表?
The issue with your current code is that the print(storage_list) statement is inside the for loop—so it runs every time you add a new element to the list. To get only the final result, you just need to move that print statement outside the loop, after all elements have been added.
Modified Code (Direct Fix)
def multiples_of_3(x, y): y = y + 1 storage_list = [] for i in range(x, y): if i % 3 == 0: storage_list.append(i) print(storage_list) # Now runs once after the loop finishes multiples_of_3(3, 9)
This will output [3, 6, 9] exactly once, which is the final list of multiples of 3 between 3 and 9.
More Pythonic Alternative (List Comprehension)
If you want to simplify the code further, you can use a list comprehension to build the list in one line, which is a common Python idiom:
def multiples_of_3(x, y): # Directly create the list of multiples without a loop storage_list = [i for i in range(x, y+1) if i % 3 == 0] print(storage_list) multiples_of_3(3, 9)
Here, we skip modifying y separately and just use y+1 directly in the range() call, which achieves the same result more concisely.
Bonus: Return the List Instead of Printing
If you want to reuse the list later (instead of just printing it), you can add a return statement:
def multiples_of_3(x, y): return [i for i in range(x, y+1) if i % 3 == 0] # Print the result when calling the function print(multiples_of_3(3, 9))
This makes the function more flexible—you can assign the result to a variable and use it elsewhere in your code.
内容的提问来源于stack exchange,提问作者Zen

