提问人:marc77 提问时间:5/13/2023 更新时间:5/13/2023 访问量:56
尝试在“if...不然......”语句,并说下面的函数没有定义
Trying to call a function in an "if... else..." statement, and its saying that the function below isn't defined
问:
y = 0
x = 10
print("TRUE" if y>x else theloop())
def theloop():
while y < 11:
print(f"Number is {y}!")
y = y + 1
我希望 y 继续变大 1,直到它变得比 x 大并打印“TRUE”,但每次它都说函数未定义。
我在这里尝试过这个,它似乎出于某种原因起作用。但是每当我想让 y 增加 1 时,它就会完全停止工作。
y=0
x=10
def theloop():
while y < x:
print(y+1)
print("true" if y>x else theloop())
答:
1赞
futium
5/13/2023
#1
首要的事:
在全局作用域中,您需要在调用函数之前定义该函数。 这就解释了为什么你的第一个代码不起作用。Python 尚未定义函数,您在它有机会访问它之前就调用了它。
print("TRUE" if y>x else theloop())
# Python hasn't seen this when you call the function
def theloop():
while y < x:
print(y+1)
第二件事:
您编写的仅运行的代码打印 (y+1)...它实际上并没有将 Y 增加 1。
此外,y 在函数中不可访问,因此:
在 while 循环之前本地定义它,如下所示:
x = 10
def the_loop():
# define y locally
y = 0
while y < x:
# increases y by 1
y += 1
print(y)
print("true" if y > x else the_loop())
如果 y 可能会更改,请将其作为参数传入:
x = 10
y = 0
# pass y in as an argument
def the_loop(y):
while y < x:
# increases y by 1
y += 1
print(y)
print("true" if y > x else the_loop(y))
使用 global 关键字(请参阅此帖子)
y = 0
x = 10
def theloop():
global y
while y < x:
y += 1
print(y)
print("true" if y > x else the_loop())
使用 global 关键字实际上会更改原始变量,现在 y = 10 可以在函数外部访问。有关全局变量的更多信息,请点击此处
评论
1赞
Mark Ransom
5/13/2023
你试过这个代码吗?我认为这行不通。
0赞
futium
5/13/2023
@MarkRansom 已修复,感谢您的注意。
2赞
Samwise
5/13/2023
值得注意的是,在第二个版本中,全局即使在 .y
the_loop
评论
y = y + 1
y
y
global y
theloop
theloop()