为何Python未用print调用函数时x、f数组仍为空?
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 namedsimpsons"—but those steps don’t run on their own. - When you add
print(simpsons(x,f)), you’re calling the function: Python jumps into thesimpsonsfunction, runs the loop that reads yourcd.txtfile, appends the values toxandf, then returns the updated lists to be printed. - If you skip that
printline (or any other call tosimpsons(x,f)), the function’s code never runs at all. That meansxandfstay 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

