Skip to content

Python control flow statements

Control flow statements allow developers to introduce logic and rules into code execution.^[400-devops__09-Scripting-Language__python__introduction__README.md] They enable the program to execute specific blocks of code conditionally based on whether certain criteria are met.^[400-devops__09-Scripting-Language__python__introduction__README.md]

If, Elif, and Else

Python uses if, elif, and else statements to handle conditional logic.^[400-devops__09-Scripting-Language__python__introduction__README.md] The if statement checks a condition, the elif statement checks additional conditions if the previous ones were false, and the else statement executes a block if none of the preceding conditions were true.^[400-devops__09-Scripting-Language__python__introduction__README.md]

In the following example, a function returns a specific customer name only if the provided customerID matches a known value:

def getCustomer(customerID):
  if customerID == "abc":
    return "Marcel Dempers"
  elif customerID == "def":
    return "Bob Smith"
  else:
    return ""

While Loops

A while loop executes a block of code as long as a specified condition remains true.^[400-devops__09-Scripting-Language__python__introduction__README.md] This is often used for iteration where the number of times the loop needs to run is not strictly known in advance, or depends on a dynamic condition.

For example, to iterate through a list of customers using a manual index counter:

i = 0
while i < 7:
  print(customers[i])
  i += 1

For Loops

for loops are used to iterate over the elements of a sequence (such as a list or a dictionary).^[400-devops__09-Scripting-Language__python__introduction__README.md] They are generally preferred over while loops when iterating over collections because they handle the iteration logic automatically.

The following example demonstrates iterating through a dictionary where customerID represents the keys:

for customerID in customers:
  print(customers[customerID])

Sources

  • 400-devops__09-Scripting-Language__python__introduction__README.md