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.

Here's another example of a while loop:

# Initialize position
pos = vec(0, 0, 0)

#Initialize velocity
v = vec(1, 0, 0)

# Counter variable
t = 0

# Increment amount
dt = 1              

# Loop!
while t <= 200:     # Conditional
    pos += v*dt     # Operation
    t += dt         # Increment
  • 184_notes/loops.1650462661.txt.gz
  • Last modified: 2022/04/20 13:51
  • by woodsna1