Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015 Interactive vs. Source code modes Q: Is source code just what we are typing into pyCharm? A: Yes! When you create a file, and put python in it, you are creating source code. When you hit “Run” in pyCharm, you are actually launching the python interpreter and sending it the file you have been editing. This is “source code” or “non-interactive” or “program” mode. When you just launch python without sending it a file, you are in interactive mode: like a calculator, you can type stuff in, and the interpreter runs it, giving back results for each line. Properties of Source Code vs. Interactive Modes Source Code Mode • Python interpreter reads code in from a file, and runs it. • Prints out results only when the code says to print something. • Exits when the code is done running. Interactive Mode • Python interpreter started without being given any code to run. • • • • • Shows a prompt: >>> Prints out result after every line is entered by the user. Does not exit until you type exit() or Ctrl-D. Very good for checking something quickly. Nothing you type in is saved for later. Augmented assignment operators Q: Can you explain how to properly use the += sign? A: What if we could write this in python?: aVal = 7 change aVal by 1 • What would that mean? • Means add 1 to the value in aVal. • aVal += 1 • Equivalent to aVal = aVal + 1 • Similarly for -= *= /= How print works… • When you call print x, y, z, w + 3, len(guests) these things happen: • Each argument to the print statement is evaluated (converted into a value). • Each value is converted to a str (if it isn’t a string already). • Essentially str(arg) is called on each. • Values are printed out with a space between each. • A newline is outputted, unless the print ends with a comma. Printing strings Q: What will the output look like?: print "Hi", "there" print "Hi" + "there" A: Hi there Hithere How many values? Q: How many values are being passed to the print command?: print "Today’s date is", month, "/", day, "/" + str(year) + "." A: 5 Practice printing Q: Write this output: for i in range(10): print i, ", ", print A: 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , (and next output is on a new line) What does this code do? What does this code output? for i in range(2, 5): print “jsv” + i Syntax error: cannot concatenate string and integer How to make it print 3 userIds correctly? for i in range(2, 5): print “jsv” + str(i) For loop syntax Q: In the first example of for loops on page 126, where did the person identifier come from? (Assume guests refers to a list.) for person in guests: print person A: The pattern for for loops is: for <loop variable> in <sequence>: <statements> If <loop variable> doesn’t exist already, python creates it, just like in an assignment. Loop variable declaration/use Q: When the code reads: for person in guests: print person are we in fact assigning the variable name person to every item in guests (in this case a list)? A: Yes! The variable person is defined and then set to iterate through each element of guests. It is just like a variable declaration in an assignment. Element-based vs. Index-based loop • A loop is a loop – the loop variable iterates through the items. • An element-based loop is just this: for elem in someList: # do something with each elem in someList. do stuff with elem • An index-based loop is the same syntax, but a different idea: • Each element in a list is at a certain index. • Access the elements via the index. for idx in range(len(someList)): do stuff with someList[idx] # sequence is indices now. When do you use which? • Element-based is so easy to read and understand. • Use when you just need each element, and • Don’t care where the element is in the list. • Index-based is more general. • • • • Use when you need to know where the element is in the list. Use when you need to iterate through multiple lists of the same length. Use when you need to access elements before or after the current idx. When you need to change contents of the list. Welcome to the Cheese Shop! Q: Write code that iterates through a list cheeses and prints out i. <the ith item in the list> for each item. A: for i in range(len(cheeses)): print str(i) + ". " + cheeses[i] (or ...) Which to use? Q: Suppose you are given 2 lists: guys and girls. guys = [“Georg”, “Homer”, “Ichabod” ] girls = [“Gertrudella”, “Helga”, “Ingmar”] Write code to print out all pairs, like Georg, Gertrudella Homer, Helga Ichabod, Ingmar A: for i in range(len(guys)): print guys[i] + ", " + girls[i] Using multiple consecutive items Write code that repeatedly prints out two consecutive items from list aList. E.g., if aList = [ “hi”, 1, True ] it will print out hi1, 1True (each on its own line). for i in range(len(aList) - 1): # generate indices 0, 1, …, n – 2. # convert each item in aList to string before concatenating. print str(aList[i]) + str(aList[i+1]) Why doesn’t this work? We want to make every string in a list all lower case: # guests is a list of strings for person in guests: person = person.lower() But, it doesn’t work. Why not? A: Because strings are immutable! So, person.lower() returns a new string, all lower-case. And, person refers to it, but the “slot” in the list does not change. How to fix this? Weird loop? Q: What is different about this for loop: for num in range(1000): val = random.randint(3) do_something(val) A: the loop variable num isn't used. This construct is how we do a loop a certain number of times. What does this do? Q: What does this code do, assuming charges is a list of floating point numbers?: total = 0.0 for charge in charges: total += charge print total A: prints the sum of all the values in charges. Challenge Q: Suppose you are given 2 lists: guys and girls. Write code to print out all possible pairs, like Georg, Gertrudella Georg, Helga ... A: for guy in guys: for girl in girls: print guy + ", " + girl Real challenge! Q: Write code to take a line of words and produce a string reversed_words that has the same words, each having been reversed. (Note: use a slice to reverse the word.) A: rev_words = [] for word in line.split(): rev_words.append(word[::-1]) reverse_words = " ".join(rev_words) More practice Given a string referred to by variable data, write code to print out its 1st letter, then 1st and 2nd letter, then first 3 letters, etc. Example: data = “CS106” Output: C CS CS1 CS10 CS106 More practice Now, write code to print it out this way: Output: C CS CS1 CS10 CS106 Practice Write code to interleave two lists. E.g., muscles = [“bicep”, “tricep”, “quad”] bones = [“elbow”, “head”, “nose”] Interleave into list mandb: [“bicep”, “elbow”, “tricep”, “head”, “quad”, “nose”] You may assume the lists are the same length. Lists of floats… Write code that creates a list of floats [0.0, 0.1, 0.2, 0.3, 0.4, … , 9.8, 9.9] Write code that starts with a list of integers iList and produces a list of floats fList where each float in fList is a float that is one-tenth of the corresponding value in iList. E.g., given iList = [3, 5, 7, -33], fList would be [0.3, 0.5, 0.7, -3.3] A really good challenge! Q: Write the loop to print out the nth Fibonacci term, assuming n >= 3. A: prev_term = prev_prev_term = 1 for i in range(3, n+1): term = prev_term + prev_prev_term prev_prev_term = prev_term prev_term = term print "nth fib is ", term