Python Control Structures
In Python, control structures are blocks of code that determine how other blocks of code are executed based on certain conditions. There are three main types of control structures in Python:
- if statements: These execute a block of code if a certain condition is true.
- for loops: These execute a block of code for a specified number of times or for each element in a sequence.
- while loops: These execute a block of code as long as a certain condition is true.
if control structure
Here is an example of an if statement in Python:
x = 5
if x > 10:
print("x is greater than 10")
else:
print("x is not greater than 10")
This code uses an if statement to check if the value of x is greater than 10. If it is, it prints “x is greater than 10”. If it is not, it prints “x is not greater than 10”. In this case, the value of x is 5, which is not greater than 10, so the code will print “x is not greater than 10”.
Following is the test case for this code:
# Test for if statement
def test_if_statement():
x = 5
result = ""
if x > 10:
result = "x is greater than 10"
else:
result = "x is not greater than 10"
assert result == "x is not greater than 10", f"Expected 'x is not greater than 10' but got '{result}'"
x = 15
result = ""
if x > 10:
result = "x is greater than 10"
else:
result = "x is not greater than 10"
assert result == "x is greater than 10", f"Expected 'x is greater than 10' but got '{result}'"
test_if_statement()
for loop
For loops and while loops have a similar syntax. Here is an example of a for loop:
for i in range(5):
print(i)
This code uses a for loop to iterate over the values in the range 0 to 4. The loop variable i is assigned each value in the range, and the code inside the loop block (print(i)) is executed for each iteration. This code will print the numbers 0 through 4.
The test case for this code is as follows:
def test_for_loop():
expected_output = [0, 1, 2, 3, 4]
result = []
for i in range(5):
result.append(i)
assert result == expected_output, f"Expected {expected_output} but got {result}"
test_for_loop()
while loop
Here is an example of a while loop:
i = 0
while i < 5:
print(i)
i += 1
This code uses a while loop to repeatedly execute the code block as long as the condition i < 5 is true. The loop variable i is initialized to 0 before the loop starts, and the code inside the loop increments i by 1 on each iteration. This code will also print the numbers 0 through 4.
Following is the test case for this code.
def test_while_loop():
expected_output = [0, 1, 2, 3, 4]
result = []
i = 0
while i < 5:
result.append(i)
i += 1
assert result == expected_output, f"Expected {expected_output} but got {result}"
test_while_loop()