184_notes:loops

This is an old revision of the document!


Coding: Loops

You can think of coding as writing instructions for a computer to follow. Let's say I want my computer to print out each of the numbers from 1 to 100. In Python, printing a number is easy:

print(1)

This will print the number 1. Printing all the numbers from 1 to 100 is a little more challenging though. Here's one way:

print(1)
print(2)
print(3)
print(4)
print(5)
...

That will take a long time to write, and physicists are lazy! This is a problem. We often want computers to repeat the same instruction (or a very similar instruction) many times in a row. Luckily, there is a solution. What do you think the following code does?

i = 1
while i <= 100:
    print(i)
    i = i + 1

You guessed it–in just a few lines, this code prints the numbers from 1 to 100. Let's break down what it's doing.

i = 1              # Counter variable
while i <= 100:    # Conditional
    print(i)       # Operation
    i = i + 1      # Increment
  • 184_notes/loops.1650157183.txt.gz
  • Last modified: 2022/04/17 00:59
  • by woodsna1