Python中函数未执行

3 投票
3 回答
12457 浏览
提问于 2025-04-15 17:20

我有一个程序,它在函数还没有定义的时候就运行了。当我把代码放进一个函数里时,它并没有执行里面的代码。为什么会这样呢?下面是一些代码:

def new_directory():

    if not os.path.exists(current_sandbox):
        os.mkdir(current_sandbox)

3 个回答

1

这段代码是用来处理一些数据的。它的主要功能是读取输入,然后进行一些计算,最后输出结果。具体来说,它可能会从一个文件或者用户输入中获取数据,然后把这些数据进行整理和分析。最后,程序会把处理后的结果显示出来,可能是打印到屏幕上,或者保存到另一个文件中。

在编程中,通常会用到循环和条件判断来实现这些功能。循环可以让程序重复执行某些操作,而条件判断则可以根据不同的情况做出不同的处理。这样,程序就能灵活地应对各种输入和需求。

总之,这段代码的目的是为了让计算机能够自动化地处理数据,减少人力的工作量,提高效率。

def new_directory():  
  if not os.path.exists(current_sandbox):  
     os.mkdir(current_sandbox)

new_directory() 
4

你的代码实际上是定义了一个叫做 new_directory 的函数。只有当你调用 new_directory() 时,这段代码才会被执行。

所以,当你想要运行你帖子里的代码时,只需要加上一个函数调用,像这样:

def new_directory():

 if not os.path.exists(current_sandbox):
   os.mkdir(current_sandbox)

new_directory()

我不确定这是不是你想要的效果。

4

问题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个空格,并且用空格而不是制表符。

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)

撰写回答