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

为何Python未用print调用函数时x、f数组仍为空?

Why does calling print(simpsons(x,f)) affect the contents of lists x and f?

Let's break down what's happening here step by step—this is a super common point of confusion when you're getting started with functions in Python.

First, here's your code again for reference:

file=open("cd.txt","r")
x=[]
f=[]
def simpsons(x,f):
    for line in file:
        y=line.split()
        x.append(float(y[0]))
        f.append(float(y[1]))
    return(x,f)
print(simpsons(x,f))

The core issue: Functions don’t run until you call them

The key misunderstanding here is that defining a function doesn’t automatically execute its code. You have to explicitly call the function for the instructions inside it to run.

  • When you write def simpsons(x,f):, you’re just telling Python "here’s a set of steps named simpsons"—but those steps don’t run on their own.
  • When you add print(simpsons(x,f)), you’re calling the function: Python jumps into the simpsons function, runs the loop that reads your cd.txt file, appends the values to x and f, then returns the updated lists to be printed.
  • If you skip that print line (or any other call to simpsons(x,f)), the function’s code never runs at all. That means x and f stay exactly as you initialized them: empty lists [].

A quick side note about mutable objects

You might also notice that even if you didn’t return (x,f) from the function, calling simpsons(x,f) would still modify the original x and f lists. That’s because lists are mutable in Python—when you pass them to a function, you’re passing a reference to the same list object, so changes like append affect the original list directly.

A small improvement for your code

While not directly related to your question, it’s a good practice to use a with statement for file handling—it automatically closes the file when you’re done, preventing resource leaks:

x = []
f = []

def simpsons(x, f):
    with open("cd.txt", "r") as file:
        for line in file:
            y = line.split()
            x.append(float(y[0]))
            f.append(float(y[1]))
    return (x, f)

# Call the function to populate the lists
simpsons(x, f)
# Now x and f have your data, even without printing
print(x, f)

内容的提问来源于stack exchange,提问作者Layla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:28:36