Control Flow - CameronAuler/python-devops GitHub Wiki
Table of Contents
Conditional Statements
if
Statements
Executes a block of code if the condition is True
.
x = 10
if x > 5:
print("x is greater than 5")
# Output:
x is greater than 5
if-else
Statements
Provides an alternate block of code when the condition is False
.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
# Output:
x is not greater than 5
if-elif-else
Statement
Handles multiple conditions by chaining elif
(else if) statements.
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
# Output:
x is greater than 5 but less than or equal to 10
Loops
for
Loop
Used to iterate over a sequence (e.g., list, tuple, string).
for i in range(5): # Iterates over 0, 1, 2, 3, 4
print(i)
# Output:
0
1
2
3
4
Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
apple
banana
cherry
while
Loop
Executes as long as the condition is True
.
count = 0
while count < 3:
print(count)
count += 1
# Output:
0
1
2
Loop Control Statements
break
Exits the loop prematurely when a condition is met.
for i in range(5):
if i == 3:
break
print(i)
# Output:
0
1
2
continue
Skips the current iteration and moves to the next.
for i in range(5):
if i == 3:
continue
print(i)
# Output:
0
1
2
4
pass
A placeholder that does nothing. Often used for future code.
for i in range(5):
if i == 3:
pass # Placeholder for future logic
print(i)
# Output:
0
1
2
3
4