Conditional statements are used to execute different blocks of code depending on conditions. Python uses if
, elif
, and else
to handle this.
Example 1: Basic conditional statements
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You are an adult, just turned!")
else:
print("You are an adult.")
Output:
You are an adult, just turned!
Example 2: Nested conditionals
age = 18
citizenship = 'US'
if age >= 18:
if citizenship == 'US':
print("You can vote.")
else:
print("You cannot vote.")
else:
print("You are too young to vote.")
Output:
You can vote.
Loops are used to repeat a block of code multiple times.
Example 1: `for` loop
for i in range(5): # Iterating through numbers 0 to 4
print(i)
Output:
0
1
2
3
4
Example 2: `while` loop
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
Loop control statements allow you to control the flow inside a loop, such as exiting early, skipping an iteration, or doing nothing.
Example 1: `break` (Exit loop)
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
Output:
0
1
2
3
4
Example 2: `continue` (Skip iteration)
for i in range(5):
if i == 3:
continue # Skip the iteration when i equals 3
print(i)
Output:
0
1
2
4
Example 3: `pass` (Placeholder)
for i in range(5):
if i == 3:
pass # Placeholder, does nothing for i == 3
else:
print(i)
Output:
0
1
2
4
The `else` block in loops executes only if the loop completes without encountering a `break`.
Example 1: `for...else`
for i in range(5):
print(i)
else:
print("Loop completed without break.")
Output:
0
1
2
3
4
Loop completed without break.
Example 2: `while...else`
count = 0
while count < 5:
print(count)
count += 1
else:
print("While loop completed without break.")
Output:
0
1
2
3
4
While loop completed without break.
Example 3: `for...else` with `break`
for i in range(5):
if i == 3:
print("Breaking the loop.")
break
else:
print("This will not be executed if break occurs.")
Output:
Breaking the loop.