在Python中定义和调用函数

时间:2011-08-11 20:32:15

标签: python function

我正在深入定义和调用函数,但我不确定我是否已经掌握了这个概念。我在python中有一个if / else语句,它循环遍历包含XML文档的文件夹。在下面的脚本中,我有一段代码,我必须在每个if xmlfilename ==条件后重新输入。

我在想,如果我将if element.tag ==开始的块定义为函数,我可以在每个条件if xmlfilename ==之后调用它。我想我已经找到了如何定义函数,但我不确定在if xmlfilename ==条件出现后我会怎么称呼它。任何人都可以建议如何做到这一点,或者我对如何定义和使用函数有所帮助?

if xmlfilename == "Soil":

  if element.tag == "timeinfo":
    tree = root.find(".//timeinfo")
    tree.clear()

    if SINGLEDATE == "'Single Date'":

        child1 = ET.SubElement(tree, "sngdate")
        child2 = ET.SubElement(child1, "caldate")
        child3 = ET.SubElement(child1, "time")


    if MULTIPLEDATES == "'Multiple Dates'":                        

        parent = ET.SubElement(tree, "mdattim")

        for x, y in enumerate(Date2.split(";")):                         
            #print x, y
            replaceMD = y.replace('/', '-')

            if x == 0:
                #print x, y
                child1 = ET.SubElement(parent, "sngdate")
                child2 = ET.SubElement(child1, "caldate")
                child3 = ET.SubElement(child1, "time")              
                child2.text = replaceMD
                child3.text = "unknown"
            else:
                child1 = ET.SubElement(parent, "sngdate")
                child4 = ET.SubElement(child1, "caldate")
                child4.text = replaceMD

if xmlfilename == "Tree":
   # Do the same thing as above starting at "if element.tag == "timeinfo":"

1 个答案:

答案 0 :(得分:2)

如果"Soil""Tree"的功能完全相同,您只需将if语句修改为以下内容:

if xmlfilename == "Soil" or xmlfilename == "Tree":
    # The rest of your code

虽然您可以选择将代码块放在函数中以更好地组织代码:

def read_xml_data():
    # Your code block

if xmlfilename == "Soil" or xmlfilename == "Tree":
    read_xml_data()

当代码块中的某些变量需要根据某个参数从一个调用更改为另一个调用时,函数更有用。例如:

def read_xml_data(param):
   if param == "value1":
      # do one thing
   elif param == "value2":
      # do something else