Control Flow Statements
1. Conditional
Statements (if, elif, else)
Conditional statements are
used to execute code based on whether a condition is True or False.
Python offers several ways to implement conditional logic using if, elif,
and else.- The if statement evaluates a
condition. If the condition is True, the block of code
indented below the if statement is executed.
x = 10
if x > 5:
print("x is greater than
5")
Output: x is greater than 5
- The else statement comes
after an if. It runs if the if 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
- The elif (short for
"else if") statement allows multiple conditions to be
checked in sequence. It runs if the if condition is False and
the elif condition is True.
- You can have multiple elif statements,
but the block will stop at the first condition that is True.
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 less than or
equal to 5")
Output: x is greater than 5 but less than or
equal to 10
2. The for...Loop
A for loop
is used to iterate over a sequence (such as a list, tuple, dictionary, set, or
string) and execute a block of code for each item.
Basic syntax:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
The for loop
can also iterate over a range of numbers using the range() function:
for i in range(5):
print(i)
Output: 0 1 2 3 4
3. The while...Loop
A while loop
repeats as long as a condition is True. It checks the condition
before each iteration, so the loop may run zero or more times.
Basic syntax:
i = 1
while i <= 5:
print(i)
i += 1
Output: 1 2 3 4 5
Be careful with while loops,
as they can result in an infinite loop if the condition never
becomes False.
4. continue Statement
The continue statement
is used to skip the rest of the code inside the current loop iteration and move
on to the next iteration.- Example:
for i in range(5):
if i == 3:
continue
print(i)
Output: 0 1 2 4
The number 3 is skipped.
5. break Statement
The break statement
is used to exit the loop immediately, skipping any remaining iterations.- Example:
for i in range(5):
if i == 3:
break
print(i)
Output: 0 1 2
The loop stops when i is 3.
The loop stops when i is 3.
6. pass Statement
The pass statement
does nothing. It is used as a placeholder when a statement is syntactically
required but no code needs to be executed. It is often used in situations where
code will be added later.- Example:
x = 10
if x > 5:
pass #
Placeholder for future code