挣扎于python赋值
嗨,我对python非常陌生,我不明白我的函数有什么问题,下面是我的代码:挣扎于python赋值,python,Python,嗨,我对python非常陌生,我不明白我的函数有什么问题,下面是我的代码: def myfunc_1(): my_file = open("ex1_sample_data.txt", "r") my_list = [] for i in my_file: my_list.append(i) return my_list print(myfunc_1()) def myfunc_2(): file = open("ex1_sample_d
def myfunc_1():
my_file = open("ex1_sample_data.txt", "r")
my_list = []
for i in my_file:
my_list.append(i)
return my_list
print(myfunc_1())
def myfunc_2():
file = open("ex1_sample_data.txt", "r")
for string_line in file:
string_line = string_line.strip()
my_tuple = myfunc_1(string_line)
my_list.append(my_tuple)
return my_list
print(myfunc_2())
每次运行它,我都会收到这样的信息:
TypeError: myfunc_1() takes 0 positional arguments but 1 was given
收到的位置参数错误表示您正在向“my_func1()”提供数据,但在函数定义中没有说明“my_func1()”接受任何内容 基本上,您需要确保我的函数1看起来像:
def my_func1(some_var):
而不是:
def my_func1():
myfunc_2中的这一行是错误的:
my\u tuple=myfunc\u 1(字符串行)
这是因为根据您对myfunc_1的定义,函数没有任何参数作为输入
你可以把它改成
my_tuple = myfunc_1()
您将看到它是有效的。您没有报告
myfunc_1()
的定义。您可以与我们共享整个代码吗?调用此函数很容易。我不确定在将代码粘贴到StackOverflow中时是否出现格式问题,但最好确保代码以4个空格的倍数缩进。欢迎使用Stack Overflow!看看这本书。如果我将ex1\u sample\u data.txt创建为一个空文件,则会出现另一个错误,namererror:name'my\u list'未在myfunc\u 2()中定义。你需要做一个决定。你可以回答这个问题。请参阅以获取其他建议。它必须是特定变量还是随机变量?这取决于您如何编写我的函数1。将它命名为对函数有意义的输入,然后可以在函数中使用该变量。因此,如果你有一个生成巧克力的函数,它可能看起来像:def brownies(巧克力、面粉、鸡蛋、糖):现在它说my_列表没有定义好,这基本上是因为myfunc_2中没有定义my_列表。您是否清楚使用这两个函数时希望得到什么?如果你解释一下,我也许能帮上忙