我正在尝试在for循环内调用函数,但未成功。 是否可以像在Excel中调用子例程一样在Python 3.x中调用函数?
这是我尝试的代码,但没有任何输出。
def my_fun1(i):
x=+i
return x
def my_func2(x1)
print(x1)
test_rng=range(124,124+100)
for i in test_rng:
my_fun1(i)
print(x)
my_fun2(x)
答案 0 :(得分:2)
是的,有可能,但是您的代码将无法运行,因为循环内的x
是未知的:
for i in test_rng:
my_fun1(i)
print(x)
my_fun2(x)
可能,您想做类似的事情:
for i in test_rng:
x = my_fun1(i)
print(x)
my_fun2(x)
您可能还需要仔细检查my_fun1()
中的代码:
def my_fun1(i):
x=+i
return x
,因为使用x=+i
可能表明您正在尝试做与x = i
不同的事情,这实际上是您的代码正在做的事情:x=+i
-> x = (+i)
- > x = i
答案 1 :(得分:1)
您的代码包含错误的逻辑,我还假设变量x
是全局定义的。见下文。
def my_fun1(i):
x=+i#I am assuming you want this x+=i
return x
def my_func2(x1)
print(x1)
test_rng=range(124,124+100)
for i in test_rng:
my_fun1(i)
print(x)
my_fun2(x)