Cheat Sheet Python For Loop

journey into python

This cheat sheet python for loop comes from the Python For Loop learning post. You can also check out Python.org for more information on For Loops. Cheat Sheet Python For Loop is one of many cheat sheets that we are creating to help everyone out. It’s for those that always forget the small things(like me).

A for loop iterates over a sequence of elements, executing the body of the loop for each element in the sequence.

Syntax:

for 'variable' in 'sequence':
    body

The range() function:

  • range() generates a sequence of integer numbers. It can take one, two, or three parameters:
  • range(n): 0, 1, 2, … n less 1
  • range(x,y): x, x+1, x+2, … y less 1
  • range(p,q,r): p, p+r, p+2r, p+3r, … q less 1 (if it’s a valid increment)

Common Mistakes:

Forgetting that the upper limit of a range() isn’t included.

Iterating over non-sequences. Integer numbers aren’t iterable. Strings are iterable letter by letter, but that might not be what you want.

Typical use:

For loops are mostly used when there’s a pre-defined sequence or range of numbers to iterate.

Break & Continue

You can interrupt the for loop using the break keyword. We normally do this to interrupt a cycle due to a separate condition.

You can use the continue keyword to skip the current iteration and continue with the next one. This is typically used to jump ahead when some of the elements of the sequence aren’t relevant.