l = [1, 2, 3, 4] s = "Abcde" #mutability l[0] = 0 #this works because lists are mutable s[0] = "a" #this throws an error because strings are immutable s = "a" + s[1:] #for loops are good for executing some code for every element #in a list or for every character in a string """ #loop over lists for elt in l: print elt #loop over strings for char in s: print char """ #given l, print whether elt is divisible by 2 """ for elt in l: if elt % 2 == 0: print "divisible by 2" else: print "not divisible by 2" """ #for loops are also good for when you know exactly how many times #you want to execute a block of code using the range function #examples: range(10) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # range(1, 5) = [1, 2, 3, 4] # range(5, 0, -1) = [5, 4, 3, 2, 1] """ #loops with range l = [] for i in range(10): l.append(i + 2) print l for i in range(5): print i """ #while loops are used when you want to execute a block of code #until a particular condition is true """ x = 10 while x > 0: # do something print x x = x - 1 #x -= 1 """ valid_inputs = ["rock", "paper", "scissors"] #player1 = raw_input("rock, paper, or scissors? ") #while input is invalid: # ask again #when code is valid, play RPS """ while player1 not in in valid_inputs: #ask again player1 = raw_input("rock, paper, or scissors? ") else: #play rps print "RPS code here" """