Presentation is loading. Please wait.

Presentation is loading. Please wait.

Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.

Similar presentations


Presentation on theme: "Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015."— Presentation transcript:

1 Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015

2 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.

3 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.

4 User vs. Programmer Just hinted at in the book A programmer needs to think about what the user sees when they run the code Is it obvious what is happening? Is the user getting the feedback they need/want? Can the user customize the output? Often, you are the programmer and the user…

5 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 -= *= /=

6 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.

7 Printing strings Q: What will the output look like?: print "Hi", "there" print "Hi" + "there" A: Hi there

8 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

9 Q3 Q: Write the output: print "I am the very model", print "of a modern major general" A: I am the very model of a modern major general

10 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)

11 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)

12 Q5 Q: What is the problem here, and how do you fix it? i = 42 print "The answer is " + i A: Problem: cannot concatenate a string and int. print "The answer is " + str(i) or print "The answer is", i

13 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 in : If doesn’t exist already, python creates it, just like in an assignment.

14 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.

15 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)): # sequence is indices now. do stuff with someList[idx]

16 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.

17 Welcome to the Cheese Shop! Q: Write code that iterates through a list cheeses and prints out i. for each item. A: for i in range(len(cheeses)): print str(i) + ". " + cheeses[i] (or...)

18 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]

19 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])

20 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?

21 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.

22 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.

23 Q13 Q: Suppose you have a sequence (a list or tuple) spanish_inquisition_essentials. Write a loop to call do_something(elem) on each element elem in the list. A: for elem in spanish_inquisition_essentials: do_something(elem)

24 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

25 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)

26 Even real-er 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


Download ppt "Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015."

Similar presentations


Ads by Google