q and a for section 4.4

21
Q and A for Section 4.4 CS 106, Fall 2015

Upload: dwayne

Post on 24-Feb-2016

31 views

Category:

Documents


0 download

DESCRIPTION

Q and A for Section 4.4 . CS 106, Fall 2013. Q1. Q: The syntax for an if statement (or conditional statement ) is: if _______________ : _____________ A: if : . Q2. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Q and A for Section 4.4

Q and A for Section 4.4

CS 106, Fall 2015

Page 2: Q and A for Section 4.4

If statement syntax

Q: The syntax for an if statement (or conditional statement) is:

if _______________ : _____________ A: if <boolean expression>: <body>

When is this used? When you have to do something when a certain condition is true, and nothing in all other cases.

Page 3: Q and A for Section 4.4

Use an if statement

Q: Write code that prints out "Brilliant!" if the value in variable food is "spam".

A: if food == "spam": print "Brilliant!"

Page 4: Q and A for Section 4.4

Compound bool expression

Q: Write code to print "Brilliant!" if food is "spam" and how_prepared is "on toast".

A: if food == "spam" and how_prepared == "on toast":

print "Brilliant!”

• If food is not “spam”, then short-circuiting is used: how_prepared won’t even be evaluated

Page 5: Q and A for Section 4.4

if-else syntax

Q: An if-else statement has this format:if _____________ : ___________else: ___________A: <boolean expression>; <if body>; <else body>

When is this used?: when there are only two choices/options, and you have to do something in each case.

Page 6: Q and A for Section 4.4

Use if-else

Q: Suppose you have a function is_prime(x) that returns True if x is a prime number. Write code to add x to a list primes if x is prime and to a list non_primes otherwise.

A: if is_prime(x): primes.append(x)else: non_primes.append(x)

Page 7: Q and A for Section 4.4

More practice

Q: Write code that prints "NaN" if the list nums is empty or, otherwise, computes and prints the average of the list of floats.

A: if len(nums) == 0:print "NaN"

else:print sum(nums) / len(nums)

Page 8: Q and A for Section 4.4

if-elif syntaxAn if-else statement has this format:if <boolean expression> : <body>elif <boolean expression> : <body># elif <boolexpr>: can repeat elif part# <body>else: # else is optional <body>When is this used? When there are > 2 choices to match and code

has to do something different for each.

Page 9: Q and A for Section 4.4

Counting

Q: You are given a long string gen containing only As, Gs, Ts, and Cs. Write code to count the number of As and the number of Gs in the string.

countAs = 0countGs = 0for ch in gen:if ch == 'A':countAs += 1elif ch == 'G':countGs += 1

Page 10: Q and A for Section 4.4

Evaluate a number

Given a variable x referring to an number, print “negative”, “0”, or “positive”, as appropriate.A:if x < 0: print “negative”elif x == 0: print “0”else: print “positive”

Page 11: Q and A for Section 4.4

Letter grades

Q: Write code to print out a student's letter grade, based on the value in score. Pick your own scale.

A: if score > 92:print 'A'elif score > 85:print 'B'elif score > 77:print 'C'

elif score > 70:print 'D'

else:print 'F'

Page 12: Q and A for Section 4.4

Nested ifs

Q: Write code to print "Brilliant!" if food is "spam" and how_prepared is "on toast", and to print "Awesome!" if how_prepared is "in a casserole".

A: if food == "spam":if how_prepared == "on toast":print "Brilliant!"if how_prepared == "in a casserole":print "Awesome!"

Page 13: Q and A for Section 4.4

Rewrite nested if as if-elif

Q: Rewrite this code using if-elif:if i < 7:

do_something(i)else:

if j > 9:do_something_else(j)

A: if i < 7:do_something(i)elif j > 9:do_something_else(j)

Page 14: Q and A for Section 4.4

Nested if vs. elif

Q: When would you prefer an if nested inside an else, over using an elif.A: An if-else is a binary decision: there are two choices. An if-elif-elif-else is an n-way decision: some variable can belong to n different “groups” or “classes”. If you are comparing a variable n to something, and then in one of the results have to “classify” some other variable, use a nested if.

Page 15: Q and A for Section 4.4

Compute the max

Given a list of positive numbers nums, write code that leaves the variable maxSeen referring to the largest number in nums. Don’t use the built-in max() function.maxSeen = 0for num in nums: if num > maxSeen: maxSeen = num

Page 16: Q and A for Section 4.4

Data cleansing

data is a list of weather readings. Each reading is a list with 10 elements. The 3th value is a temperature reading. But sometimes our thermometer goes haywire and reports the temp as -999. In this case, we want to throw out the entire reading. Write a for loop to do this, building a new list called good_data that contains only the good readings. E.g.: data = [ [ 0, 1, 2, 78, 4, 5, 6, 7, 8, 9 ], [ 0, 1, 2, -999, 4, 5, 6, 7, 8, 9 ] ]

Page 17: Q and A for Section 4.4

Answergood_data = []for aReading in data: # aReading is a list with 10 elements. # Check if the temp is not bogus. if aReading[3] != -999: good_data.append(aReading)# now good_data is clean.

Now, add code to also filter out humidity readings (in the 7th field) when they are negative.Now, add code to also filter out any readings that don’t have 10 fields in them.

Page 18: Q and A for Section 4.4

Non-booleans used as booleans

Q: In the “for the guru” on page 142, there is code if not dinner:. Can you explain that?

A: Why, yes. Yes, I can. The pattern is if <boolean expression>:

So, if the expression given is not a boolean (dinner is a string), then it is converted to a boolean, as if bool(dinner) were called. In general, if a value is empty (“” or []), the value is False; else, True.

Page 19: Q and A for Section 4.4

Checking if a value is one of many

Q: Write code that prints "Let's go" if the variable response equals either 'y' or 'yes'.

A: if response in ('y', 'yes'):print "Let's go"

(not if response == 'y' or 'yes' !!)

Page 20: Q and A for Section 4.4

What kind of triangle?

Suppose we have 3 values, s1, s2, and s3, that represent the lengths of the 3 sides of a triangle.Print out “equilateral” if the sides represent an equilateral triangle, “isosceles” for isosceles, or “scalene” otherwise.

Page 21: Q and A for Section 4.4

Simulating bouncing particles

Suppose we are simulating n particles bouncing off the inside of a container’s walls. We have 3 lists: turts is a list of Turtle objects; xvels is a list of x velocities; yvels is a list of y velocities. The next location of a turt is computed by:(turts[i].getX() + xvels[i], turts[i].getY() + yvels[i])Write code to switch the velocities (from positive to negative or vice-versa) if turts[i] is currently within 3 pixels of the walls of a 600x400 canvas.