TECHNOLOGIESTieInn Technologies

Conditions and loops

Python · 17 questions

Short notes

Key idea

if chooses which code runs; loops repeat code. for walks over a collection, while repeats until a condition turns false.

Syntax

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"

for item in items:
    ...
for i in range(5):        # 0, 1, 2, 3, 4
    ...
while balance > 0:
    balance -= 100

break leaves the loop; continue skips to the next round.

Example

orders = [450, 1200, 80, 3000]
big = 0
for amount in orders:
    if amount < 100:
        continue
    if amount > 1000:
        big += 1
print(big)   # 2

Traps

  • Indentation is the block. A line indented differently belongs to a different block.
  • range(5) stops before 5.
  • A while that never changes its condition runs forever.
  • Order of elif matters: the first true branch wins.
  • Don't change a list while looping over it; loop over a copy or build a new list.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Conditions and loops

  1. Question 1easy

    Which numbers does range(1, 5) produce?

  2. Conditions and loops

  3. Question 2medium

    What does this print?

    price = 650
    if price < 1000:
        band = "Budget"
    elif price < 700:
        band = "Cheap"
    else:
        band = "Other"
    print(band)
  4. Conditions and loops

  5. Question 3medium

    What does this print?

    total = 0
    for q in [1, 2, 5, 2]:
        if q >= 2:
            total += q
    print(total)
  6. Conditions and loops

  7. Question 4medium

    What does this print?

    count = 0
    for n in [3, 0, 4, -1, 5]:
        if n == 0:
            continue
        if n < 0:
            break
        count += 1
    print(count)
  8. Conditions and loops

  9. Question 5easy

    What does this print?

    amount = 4500
    if amount > 5000:
        print("Free delivery")
    else:
        print("Delivery ₹50")

12 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.