Conditional Statements
An if statement evaluates a boolean predicate and executes its body only when the predicate resolves to True.
limit = 20
current = 15
if current < limit:
print("Within bounds")
When a binary decision is required, the else keyword defines the alternative path.
temperature = 4
if temperature <= 0:
state = "Frozen"
else:
state = "Liquid"
For multiple exclusive possibilities, chain elif clauses after the initial if. The first matching branch executes and remaining conditions are skipped.
marks = 88
if marks >= 90:
rating = "Excellent"
elif marks >= 80:
rating = "Good"
elif marks >= 70:
rating = "Average"
elif marks >= 60:
rating = "Pass"
else:
rating = "Fail"
Python also supports a compact conditional expression that selects between two values.
access = "Granted" if authenticated else "Denied"
Decisions can be layered hierarchically by nesting conditional blocks.
x = 12
if x > 10:
if x % 2 == 0:
print("Large even number")
else:
print("Large odd number")
elif x > 5:
print("Medium value")
else:
print("Small value")
Iteration Mechanisms
Repetition in Python centers on two constructs. Use for when the iteration count is predetermined, and while when termination depends on a dynamic state.
The for Statement
The for loop traverses an iterable. When combined with range, it generates numeric sequecnes. An optional else clause executes after normal completion.
for step in range(1, 6):
print(f"Iteration {step}")
else:
print("Sequence complete")
The range function accepts one to three arguments:
range(stop)yields0throughstop - 1range(start, stop)yieldsstartthroughstop - 1range(start, stop, step)yields values fromstarttowardstopusing the specified stride
A common pattern accumulates values across a sequence.
accumulator = 0
for n in range(1, 101):
accumulator += n
Filtering by parity is equally straightforward.
even_total = 0
for n in range(2, 101, 2):
even_total += n
Nested for loops handle multi-dimensional patterns such as tabular data.
for row in range(1, 10):
for col in range(1, row + 1):
print(f"{col}×{row}={row * col}", end="\t")
print()
The while Statement
A while loop re-evaluates its condition before every repetition. An else clause runs if the loop exits normally.
energy = 3
while energy > 0:
print(f"Operating with energy level {energy}")
energy -= 1
else:
print("Shutdown complete")
If the condition never becomes false, the loop runs forever unless interrupted externally.
sequence = 0
while True:
print(f"Processing {sequence}")
sequence += 1
if sequence >= 4:
break
Loops may be nested to produce complex control patterns.
outer = 0
while outer < 3:
inner = 0
while inner < 3:
print(outer, inner)
inner += 1
outer += 1
The following snippet demonstrates a number-guessing game using indefinite iteration.
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess == secret:
print(f"Correct in {attempts} tries!")
break
elif guess < secret:
print("Too low")
else:
print("Too high")
Altering Loop Behavior
break exits the surrounding loop immediately.
for value in range(100):
if value == 7:
break
print(value)
continue abadnons the current iteration and advances to the next.
for value in range(6):
if value == 3:
continue
print(value)
pass acts as a syntactic placeholder where a statement is required but no action is desired.
if user_input == "admin":
pass # Privilege escalation logic pending