Key Concepts

Review core concepts you need to learn to master this subject

Python For Loop

for <temporary variable> in <list variable>: <action statement> <action statement> #each num in nums will be printed below nums = [1,2,3,4,5] for num in nums: print(num)

A Python for loop can be used to iterate over a list of items and perform a set of actions on each item. The syntax of a for loop consists of assigning a temporary value to a variable on each successive iteration.

When writing a for loop, remember to properly indent each action, otherwise an IndentationError will result.

Loops
Lesson 1 of 2
  1. 1
    How do we use code to tell a computer this: “Create a variable and call a function 15 times”? We could write it out 15 times: create a variable call a function create a variable call a function …
  2. 2
    When we give instructions once and tell the computer how many times to repeat them, we are using a for loop, or a count-controlled loop. It executes a set of instructions for a specified numb…
  3. 3
    What if you approached tile-placing another way: you don’t know how many tiles to place, but you know when to stop. How could you communicate this type of command to a computer? Give it the instruc…
  4. 4
    There’s one more way to give looping instructions to a computer. We define a sequence of desired tile colors (a list), and tell the computer to repeat the instructions for each item in the sequen…
  5. 5
    Let’s combine all that we’ve learned so far: * variables, operators, and data types * functions and control flow * lists and loops Examples of for and while loops are provided below in JavaScript….
  6. 6
    Well done! Loops are commonly used in programming because they save time, reduce error, and are easy to read. Being comfortable with each type of loop will make you a better programmer. In review: …