Defining and Calling Functions in Python
I am diving into defining and calling functions, but I'm not sure if I have grasped the concept. I have an if/else statement in a python that loops through a folder containing XML documents. In my script below, I have a block of code that I have to re-type after each if xmlfilename ==
condition.
I'm thinking that if I define the block starting at if element.tag ==
as a function, I can just call it after each conditional if xmlfilename ==
I think I've figured out how to define the function, but I'm not sure how I would call it after the if xmlfilename ==
condition arises. Can anyone suggest how to do this or am I way off on how defining and using functions works?
if xmlfilename == "Soil":
if element.tag == "timeinfo":
tree = root.find(".//timeinfo")
tree.clear()
if SINGLEDATE == "'Single Date'":
child1 = ET.SubElement(tree, "sngdate")
child2 = ET.SubEleme开发者_开发问答nt(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":"
If the functionality is exactly the same for "Soil"
and "Tree"
you can just modify the if statement to the following:
if xmlfilename == "Soil" or xmlfilename == "Tree":
# The rest of your code
Although you may choose to put your code block in a function to organize your code a bit better:
def read_xml_data():
# Your code block
if xmlfilename == "Soil" or xmlfilename == "Tree":
read_xml_data()
Functions are even more useful when some variables in your code block need to change from one invocation to another based on some parameter. For example:
def read_xml_data(param):
if param == "value1":
# do one thing
elif param == "value2":
# do something else
精彩评论