Ctrl-S
to save current file (check for blue dot)Ctrl-Z
to undohandin21
to submitup
and down
arrow keys will cycle through previous commandstab
will try to auto-complete filenames, directories or commandstab
twice will show options if it cannot auto-completehandin21
before Saturday nightfor
loopsrange
functionTo this point, all of our programs have been sequential - with one line of code following the other. Often, we need to repeat a task several times. If we know the number of times, we use definite loops which are called for loops in Python. The syntax is:
for VAR in SEQUENCE:
BODY
For example, we can print numbers 1 through 5:
for i in [1,2,3,4,5]:
print(i)
i
is our loop variable - it keeps track of where we are in the sequence. Defining the sequence explicitly does not scale to large numbers (e.g., 1000) so we instead use the range(x)
operator:
for i in range(5):
print(i)
which outputs:
0
1
2
3
4
What is the output of this loop?
for i in [0,1,2,3]:
print(i*2)
Notice the special syntax that uses brackets around a sequence. This is how we designate a value of type list
. A list
is a collection of values itself, which can be of any type (e.g., int
in the above example). Now try this example where the list consists of a sequence of strings:
print("Pets:")
for animal in ["Corgis", "Cavaliers", "Mini Ponies"]:
print(animal)
print()
print("Done!")
cd
cd cs21/inclass/w02-nums-strs-loops
atom ./
Open loop.py
to get some practice writing loops by completing one or more of the following tasks:
tricky
three times, once per line, using a loop.i
by adding 1 and squaring the value.