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

Q and A for Section 2.9, 4.1

Embed Size (px)

DESCRIPTION

Q and A for Section 2.9, 4.1. Victor Norman CS106 Fall 2014. Interactive vs. Source code modes. Q: Is source code just what we are typing into pyCharm ? - PowerPoint PPT Presentation

Citation preview

Page 1: Q and A for Section 2.9, 4.1

Q and A for Sections 2.9, 4.1

Victor NormanCS106

Fall 2015

Page 2: Q and A for Section 2.9, 4.1

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.

Page 3: Q and A for Section 2.9, 4.1

Properties of Source Code vs. Interactive ModesSource 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.

Page 4: Q and A for Section 2.9, 4.1

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

Page 5: Q and A for Section 2.9, 4.1

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.

Page 6: Q and A for Section 2.9, 4.1

Printing strings

Q: What will the output look like?:print "Hi", "there"print "Hi" + "there"

A: Hi thereHithere

Page 7: Q and A for Section 2.9, 4.1

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

Page 8: Q and A for Section 2.9, 4.1

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)

Page 9: Q and A for Section 2.9, 4.1

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 integerHow to make it print 3 userIds correctly?for i in range(2, 5):

print “jsv” + str(i)

Page 10: Q and A for Section 2.9, 4.1

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.

Page 11: Q and A for Section 2.9, 4.1

Loop variable declaration/use

Q: When the code reads: for person in guests: print personare 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.

Page 12: Q and A for Section 2.9, 4.1

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]

Page 13: Q and A for Section 2.9, 4.1

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.

Page 14: Q and A for Section 2.9, 4.1

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

Page 15: Q and A for Section 2.9, 4.1

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, likeGeorg, Gertrudella

Homer, Helga

Ichabod, Ingmar

A: for i in range(len(guys)):print guys[i] + ", " + girls[i]

Page 16: Q and A for Section 2.9, 4.1

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

Page 17: Q and A for Section 2.9, 4.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?

Page 18: Q and A for Section 2.9, 4.1

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.

Page 19: Q and A for Section 2.9, 4.1

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.

Page 20: Q and A for Section 2.9, 4.1

Challenge

Q: Suppose you are given 2 lists: guys and girls. Write code to print out all possible pairs, like

Georg, GertrudellaGeorg, Helga... A: for guy in guys: for girl in girls: print guy + ", " + girl

Page 21: Q and A for Section 2.9, 4.1

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)

Page 22: Q and A for Section 2.9, 4.1

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:CCSCS1CS10CS106

Page 23: Q and A for Section 2.9, 4.1

More practice

Now, write code to print it out this way:Output: C CS CS1 CS10 CS106

Page 24: Q and A for Section 2.9, 4.1

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.

Page 25: Q and A for Section 2.9, 4.1

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]

Page 26: Q and A for Section 2.9, 4.1

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