xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Loops

Basics9 min readLesson 7 of 8

A loop runs the same indented block more than once. Python has two common forms. A for loop takes items from a sequence one at a time, such as a list or a range of numbers. A while loop repeats as long as a condition stays True. Writing the same lines by hand makes a program harder to change.

python
for step in range(1, 4):
    label = f'Step {step}'
    print(label)

Output

Step 1
Step 2
Step 3

7.1 Choosing the form

  • Use for when the amount of work is known.
  • Use while when the stopping point depends on something that changes inside the loop.
  • Add a line inside every while loop that moves the condition toward False.

7.2 How range counts

range(1, 4) produces 1, 2, and 3; the second number is a stopping point that is not included. To include the endpoint, add one: range(1, 5) gives 1 through 4. A loop variable, here step, takes a new value on each pass. Indented lines repeat, and an unindented line after the block runs once.

python
count = 3
while count > 0:
    print(count)
    count -= 1
print('lift off')

Output

3
2
1
lift off

7.3 Common mistake

A while loop that never changes the variable in its condition keeps running. The body may run without end, and the terminal keeps printing until you interrupt it. Check that one line inside the loop moves the count or state toward the stopping condition. A for loop avoids that risk for simple counting, though its range still stops before the second number.

python
total = 0
for n in [2, 4, 6]:
    total += n
print(total)

Output

12

7.4 Practice

  1. Use a for loop to print the squares of 1 through 5.
  2. Rewrite the same loop with while and keep a running total.
  3. Print the total after the loop ends.

If the while version hangs, stop it and check which line is supposed to change the counter.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01When should you use a `for` loop instead of a `while` loop?

    Use `for` when you are processing the items of a sequence or a known range. Use `while` when repetition depends on a condition that changes during the loop.

  • 02What numbers does `range(2, 6)` produce?

    `2`, `3`, `4`, and `5`. The stop value is excluded.

  • 03Why might a `while` loop never finish?

    The condition stays true because no line inside the loop changes the value being tested. Update that value, or use a clear stopping condition.