Created
March 29, 2012 12:52
-
-
Save dhconnelly/2237189 to your computer and use it in GitHub Desktop.
for loops tutorial for GSMST number theory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# what if we have a list, and we want to do something for each item. | |
nums = [12, 5, 7, 18, 127, -1337] | |
# we will print out each number squared | |
# this means: repeatedly take one element from the list "nums" | |
# call it "num" | |
# and do the stuff in the for loop body. | |
for num in nums: | |
print num * num | |
for chan in nums: | |
print chan * chan | |
# what if we want to write a loop that runs 10 times | |
i = 0 | |
while i < 10: | |
print i | |
i += 1 | |
# same thing as our for loop: | |
i = 0 | |
while i < len(nums): | |
print nums[i] * nums[i] | |
i += 1 | |
# instead, we can write | |
for i in xrange(10): | |
print i | |
names = [] # this is [ ]. this is called a LIST | |
while True: | |
name = raw_input('Enter a name: ') | |
if name == 'quit': | |
break | |
names.append(name) # this adds "name" to the end of the list "names" | |
for name in names: | |
print name + 'ACK' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment