Python control flow patterns¶
Python control flow patterns allow developers to implement logic and rules within their code, dictating the execution path based on specific conditions^[400-devops-09-scripting-language-python-introduction-readme.md]. The primary mechanism for this is the if, elif, and else structure^[400-devops-09-scripting-language-python-introduction-readme.md].
Conditional Statements¶
Control flows are used to apply rules such that "if this is the case, then do that, else do something else"^[400-devops-09-scripting-language-python-introduction-readme.md]. This enables functions to perform different actions or return specific data depending on the inputs provided^[400-devops-09-scripting-language-python-introduction-readme.md].
Example Pattern¶
A common pattern involves validating an input, such as a customerID, against multiple expected values^[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 ""
In this example, the function checks the input sequentially^[400-devops-09-scripting-language-python-introduction-readme.md]:
* If customerID matches "abc", it returns the specific name associated with that ID^[400-devops-09-scripting-language-python-introduction-readme.md].
* If that condition is not met, it checks the elif condition for "def"^[400-devops-09-scripting-language-python-introduction-readme.md].
* If no conditions are met, the else block executes, returning an empty string^[400-devops-09-scripting-language-python-introduction-readme.md].
Related Concepts¶
- [[Python]]
- Python loops
- Python functions
- [[Python variables]]
Sources¶
^[400-devops-09-scripting-language-python-introduction-readme.md]