Apex Vision AI

Your Genius Study Assistant

Using if, for, and while Loops in Python Definition and Explanation if statement: Used for conditional execution. It runs a block of code only if a specified condition is true. for loop: Used for iterating over a sequence (like a list, tuple, or range).

Python Programming

How do I use if, for, and while loops in Python?

Using if, for, and while Loops in Python

Definition and Explanation

  • if statement: Used for conditional execution. It runs a block of code only if a specified condition is true.
  • for loop: Used for iterating over a sequence (like a list, tuple, or range).
  • while loop: Repeats a block of code as long as a condition remains true.
  • Syntax Overview

  • If statement:
  • ``python
    if condition:

    code block

    elif another_condition:

    another block

    else:

    else block

    `

  • For loop:
  • `python
    for variable in sequence:

    code block

    `

  • While loop:
  • `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:

    1. for i in range(1, 11):

    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
    `


    Takeaways

  • Use if for conditional logic, for for iterating over sequences, and while` 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.
W

Walsh Pex

Walsh Pex is an educational technology specialist with over 8 years of experience helping students overcome academic challenges. He has worked with thousands of students across all education levels and specializes in developing AI-powered learning solutions that improve student outcomes.

Verified Expert
Last updated: January 25, 2026

Need More Help?

Get instant AI-powered answers for any homework question with ApexVision AI

Try ApexVision Free →