Skip to content

Python functions

In Python, functions are used to execute a block of code, allowing for the organization and reuse of logic^[400-devops__09-Scripting-Language__python__introduction__README.md]. A primary design goal for a function is to give it a single purpose, which simplifies testing and maintenance^[400-devops__09-Scripting-Language__python__introduction__README.md].

Definition and Structure

A function is defined using the def keyword followed by the function name and parentheses. To execute the code within the function, it must be invoked (called) by its name^[400-devops__09-Scripting-Language__python__introduction__README.md].

def main():
    print("Hello, world.")

main()

Data Encapsulation

Functions allow details about how data is retrieved—such as from a database or file—to be hidden from the caller^[400-devops__09-Scripting-Language__python__introduction__README.md]. This abstraction means the function can return data without exposing its underlying data provider^[400-devops__09-Scripting-Language__python__introduction__README.md].

def getCustomer():
  return "Marcel Dempers"

print(getCustomer())

Inputs and Return Values

Functions typically accept inputs (parameters) and return outputs^[400-devops__09-Scripting-Language__python__introduction__README.md]. Inputs allow the function to perform operations based on dynamic data passed during the call^[400-devops__09-Scripting-Language__python__introduction__README.md].

def getCustomer(customerID):
  return "CustomerID: " + customerID + ", Name: Marcel Dempers"

print(getCustomer("abc"))

Logic and Control Flow

[[Control flow]] structures, such as if, elif, and else, are used within functions to apply logical rules^[400-devops__09-Scripting-Language__python__introduction__README.md]. This allows a function to return different results based on specific conditions, such as matching an input ID^[400-devops__09-Scripting-Language__python__introduction__README.md].

def getCustomer(customerID):
  if customerID == "abc":
    return "Marcel Dempers"
  elif customerID == "def":
    return "Bob Smith"
  else:
    return ""
  • [[Python Classes]] (for grouping variables and functions)
  • Python Loops (for iterating over data returned by functions)
  • [[Python Variables]]

Sources

^[400-devops__09-Scripting-Language__python__introduction__README.md]