Using if, for, and while Loops in Python
Definition and Explanation
ifstatement: Used for conditional execution. It runs a block of code only if a specified condition is true.forloop: Used for iterating over a sequence (like a list, tuple, or range).whileloop: Repeats a block of code as long as a condition remains true.- If statement:
- For loop:
- While loop:
- for i in range(1, 11):
- Use if
for conditional logic,forfor iterating over sequences, andwhile` for repeating code with a condition. - Combine these constructs for more complex logic and control flow.
- Understanding their syntax and use cases is fundamental for Python programming.
Syntax Overview
``python
if condition:
code block
elif another_condition:
another block
else:
else block
`
`python
for variable in sequence:
code block
`
`python
while condition:
code block
`
Worked Example
Problem: Print all even numbers from 1 to 10 and state whether each is greater than 5.
`python`
for i in range(1, 11):
if i % 2 == 0:
print(i, "is even", end="; ")
if i > 5:
print("greater than 5")
else:
print("not greater than 5")
Step-by-step explanation:
Loops through numbers $1$ \to $10$. 2. `if i % 2 == 0:` Checks if $i$ is even (since $i mod 2 = 0$). 3. If even, prints the number and checks if $i > 5$. 4. Prints whether the number is greater than $5$ or not.
Sample Output:
``
2 is even; not greater than 5
4 is even; not greater than 5
6 is even; greater than 5
8 is even; greater than 5
10 is even; greater than 5