πŸ–₯️
Berkeley CS61A: Notes
  • 🌍Hello, World!
  • πŸ’­Learn to Think Like Your Computer
  • Building Blocks
    • ❗Expressions in Python
      • ℹ️Mathematical Statements
      • 🀫Variables
      • πŸ‘Data Types in Python
    • 🚧Introduction to Functions
      • πŸƒβ€β™€οΈHow Python Executes a Function Call
      • 🚱Functions that Don't Return Anything
    • 🌊Control Flow
      • ⁉️What is an if statement?
      • πŸ’ΎWhat is a Loop?
      • 🚨What are Logical Operators?
        • πŸ˜–Logical Operators, Seemingly Illogical Behavior
      • 🚰How Does Control Flow?
    • ⚑Higher-Order Functions
      • ⏸️What are Higher-Order Functions Used For?
      • πŸ‘†Self-Reference
    • πŸ‘ΎEnvironments and Scope
      • πŸ–ŠοΈHow to Make Environment Diagrams
  • STRUCTURES OF DATA
    • ➰Recursion
      • πŸ«€Anatomy of Recursion
      • β›½Recursive Leap of Faith
    • πŸŽ„Tree Recursion
      • ⬇️The Use It/Lose It Principle
    • πŸ“€Iterables
      • βœ‚οΈList Slicing
      • πŸ’€Deep Lists
      • πŸŒ‹Iterable Functions
      • πŸ’½List Comprehensions
    • πŸ™ˆAbstraction
    • Trees
    • Linked Lists
    • Iterators and Generators
    • Efficiency
  • Extra Topics
    • 🎭Errors and their Types
      • 🏹Error vs Exception
      • πŸ”™What is Backtracing?
    • 🚑How the Terminal and the File are Different
    • 🍬Decorators
  • Debugging Tools
    • πŸ–¨οΈDebugging with Print Statements
    • πŸ›Debugging with the Debugger
Powered by GitBook
On this page

Was this helpful?

  1. Building Blocks
  2. Control Flow

What is a Loop?

While and For, among other things.

Say, we want to print "Hello!" 3 times. One might consider doing it like this:

print("Hello!")
print("Hello!")
print("Hello!")

What if you wanted to print the same thing, say, a hundred times? It is clearly impractical to write this statement a hundred times. Instead, we'll use loops to execute this block of code.

This can be done through various different syntaxes. First, we introduce the for loop:

for i in range(100):
    print("Hello!")

Next, we show how you can write the same piece of code using a while loop:

i = 100
while i != 0:
    print("Hello!")
    i = i - 1

The Anatomy of a Loop

A loop has four parts:

  • Initialization: Setting up the initial, starting value for the variable that our loop uses.

  • Condition: The condition statement, which stops the looping when it becomes false.

  • Execution Suite: The code inside the loop that gets executed every time the loop runs.

  • Updation: Updating the looping variable to get us closer to making the condition false.

We use the while loop to mark out these four sections.

i = 100 # initialization
while i != 0: # condition
    print("Hello!") # execution suite
    i = i - 1 # updation

A for loop is similar, but with lots of this stuff hidden away behind the scenes. We iterate over the range, such that range is defined as range(start=0, stop, step=1) where our values start at start (inclusive), end at stop (exclusive) and proceed by step. As an example, range(1, 5, 2) would return the values 1 and 3. The default values for start and step are 0 and 1 respectively. Thus, something like

for i in range(10):
    print(i)

Prints out all the numbers from 1 to 9.

Difference between a for and a while loop

So when do we use a for loop and when do we use a while loop? There isn't any hard and fast rule, but the general rule of thumb is this: if we have a fixed number of times we want to loop over a piece of code, use a for loop. If the number of times we loop over something depends over a condition without a fixed number, use a while loop.

We'll attempt enough examples with both to get intuition about when to use which one!

PreviousWhat is an if statement?NextWhat are Logical Operators?

Last updated 3 years ago

Was this helpful?

🌊
πŸ’Ύ