2024-04-27 03:03:31 发布
网友
我有一个程序,在没有定义函数的情况下运行。当我将代码放入一个函数时,它不会执行它包含的代码。有人知道为什么吗?其中一些代码是:
def new_directory(): if not os.path.exists(current_sandbox): os.mkdir(current_sandbox)
谢谢
def new_directory(): if not os.path.exists(current_sandbox): os.mkdir(current_sandbox) new_directory()
您的代码实际上是new_directory函数的定义。除非调用new_directory(),否则将不会执行它。 因此,当您想从post中执行代码时,只需添加如下函数调用:
new_directory
new_directory()
不确定这是否是你期望得到的行为。
问题1是您定义了一个函数(“def”是“define”的缩写),但您没有调用它。
def new_directory(): # define the function if not os.path.exists(current_sandbox): os.mkdir(current_sandbox) new_directory() # call the function
问题2(还没有击中你)是你在使用一个全局(current_sandbox)时应该使用一个参数——在后一种情况下,你的函数通常是有用的,甚至可以从另一个模块调用。问题3是不规则缩进——使用缩进1将导致任何必须阅读您的代码(包括您自己)的人发疯。坚持4,使用空格,而不是制表符。
current_sandbox
def new_directory(dir_path): if not os.path.exists(dir_path): os.mkdir(dir_path) new_directory(current_sandbox) # much later new_directory(some_other_path)
您的代码实际上是
new_directory
函数的定义。除非调用new_directory()
,否则将不会执行它。 因此,当您想从post中执行代码时,只需添加如下函数调用:不确定这是否是你期望得到的行为。
问题1是您定义了一个函数(“def”是“define”的缩写),但您没有调用它。
问题2(还没有击中你)是你在使用一个全局(
current_sandbox
)时应该使用一个参数——在后一种情况下,你的函数通常是有用的,甚至可以从另一个模块调用。问题3是不规则缩进——使用缩进1将导致任何必须阅读您的代码(包括您自己)的人发疯。坚持4,使用空格,而不是制表符。相关问题 更多 >
编程相关推荐