Python Loops and Logic


Python loops are control flow structures used to repeatedly execute a block of code.

  • two types:
    • for
      • used to iterate over a sequence or other iterable object
    • while
      • used to repeatedly execute a block of code as long as a certain condition is True

Constructing while Loops

subnet = "192.168.1."
ip_addresses = []
i = 1
 
while i < 256:
    ip_addresses.append(subnet + str(i))
    i += 1
 
for ip in ip_addresses:
    print(ip)

Incrementing in while Loop

  • incrementing increases a counter variable
  • need to prevent the loop from running indefinitely
i = 0
while i < 5:
    print(i)
    i += 1  # Increment

break Statement

The break statement in Python is used to exit a loop prematurely.

  • used when there’s a need to stop the loop before the condition is False
subnet = "192.168.1."
ip_addresses = []
i = 1
 
while True:
    if i > 255:
        break
    ip_addresses.append(subnet + str(i))
    i += 1
 
for ip in ip_addresses:
    print(ip)

continue Statement

The continue statement in Python is used in loops to skip the rest of the current iteration and move directly to the next one.

subnet = "192.168.1."
ip_addresses = []
i = 0
 
while i < 256:
    i += 1
    if i == 100:  # Let's say we want to skip this IP
        continue
    ip_addresses.append(subnet + str(i))
 
for ip in ip_addresses:
    print(ip)

else Statement

The else statement in a Python while loop specifies a block of code to be executed when the loop condition becomes False.

  • only executes after the loop finishes, not when exited with break
subnet = "192.168.1."
ip_addresses = []
i = 0
 
while i < 256:
    i += 1
    ip_addresses.append(subnet + str(i))
else:
    print("All IP addresses have been generated.")
 
for ip in ip_addresses:
    print(ip)

Constructing for Loops

for loop in Python is a control flow statement that allows code to be executed repeatedly.

for variable in iterable:
    # code to be executed
  •  iterable is a collection of objects
  •  variable takes the value of the next item in the iterable each time through the loop

for Loops vs while Loops

  • both are control flow statements
    • differ in usage and control conditions
    • for loop
      • is used for iterating over a sequence
      • the set of statements is executed once for each item in the list
      • loop continues until it has gone through each item in the sequence
      • typically used when number of iterations is known or finite
    • while loop
      • used when a set of statements needs to be executed until a condition is false
      • condition is checked before each iteration
      • used when number of iterations is unknown or infinite

Looping Through a String

  • Python has built-in support for string iteration
for character in string:
	# code to be executed
  • string is the string that needs to be iterated over
  • character is the variable that takes the value of each character in the string for each iteration

Example

ip_address = "192.168.1.1"
octets = ip_address.split(".")
octet_count = 0
 
for octet in octets:
    if octet.isdigit() and 0 <= int(octet) <= 255:
        octet_count += 1
 
print(f"The IP address {ip_address} has {octet_count} octets.")

range() Function

The range() function in Python is used to generate a sequence of numbers within a given range.

  • used in for loops when there’s a need to repeat an action a specific number of times
  • Syntax: range(start, stop, step)
    • start: An integer number specifying at which position to start. Default is 0
      • Optional
    • stop: An integer number specifying at which position to stop (not included)
    • step: An integer number specifying the incrementation. Default is 1
      • Optional
subnet = "192.168.1."
ip_addresses = [subnet + str(i) for i in range(1, 256)]
 
for ip in ip_addresses:
    print(ip)

pass Statement

The pass statement in Python is a placeholder statement that is used when the syntax requires a statement, but no action needs to be taken.

for variable in iterable:
    # code to be executed
    pass  # no action taken