DAY 6 note: 095421 is invalid, but actually not all ints with leading 0's are invalid. 0432 is fine; 282 is printed. 0432 means: 432 in octal, base 8. :-) For the curious, I added some information to the handout for lab3... Booleans, continued # not x == 5 not x ==5 x == 6 not x ==6 # and True if both are True; false, otherwise (x == 5) and (y == 6) (x == 5) and (y == 5) (x == 0) and (y == 0) # or tall = True woman = True short = False man = False # tall or short man or woman tall or woman short or man # only if BOTH are False is the result False # more practice False or True False and False False and True not not 5 == 7 not not 5 == 5 Of course, we can combine these: (False or True) and (False or True) (False and False) or (False or True) == Boolean representation == - False is stored internally as 0, and True as 1, with interesting effects: False == 0 True == 1 False < True - Even though True is 1, when checking a boolean condition, Python treats any non-zero number as True if 9.2423: print "yes" - QU: For fun, what does this do? num = 6 if num == 10 or 20 or 30: print "yes" else print "no way" It prints 'yes'! 6 == 10 or 20 or 30 num is non-zero, which is the same as True 10 or 20 or 30 10, 20, 30 are non-zero, so each of these is True so, the test is: True == True or True or True True ** TERRIBLE style, though ** == Lazy evaluation == - Programming languages, including Python, are "lazy" when it evaluates boolean expressions. x and y: if x is false, no need to evaluate y. x or y: if x is true, no need to evaluate y. - We can often take advantage of this to simplify our code. - we'll see this again. == if-statements == Remind the students of the Design-Code-Verify cycle: Design: determine what you'd like the code to do - make sure you can do it as a human! Code: write and code in small pieces Verify: test your code by running to confirm that works as expected - We'd like a function that comments about the current temperature. - It should have a different opinion for temperatures above, below, and at the freezing point. def temperature_report(temperature): '''Report on the temperature. Parameter temperature is a float''' if temperature > 32.0: print "Cookin!" elif temperature == 32.0: print "Chillin!" else: print "Brrrrrrrrr!!!!!!!" if __name__ == '__main__': temp = raw_input("Enter a temperature: ") print temperature_report(float(temp)) - Walk through this example several times in the debugger showing the different paths of execution. - Let's verify! What are the the "interesting values"? It's based on the paths through this function. For this code, we need to test 3 cases (< 0, 0, > 0). == Strings == - more about strings: 'cs401' # Use single our double quotes "cs401" 'cs401" # But don't mix them 'cs' + '401' # "+" glues two strings together; called "concatenation" # (or adds two numbers) # It's "overloaded." It knows what to do by looking at # the type of the operands. 'cs' + 401 # error; why? # Can't mix string and int operands to "+" str(401) # But you can turn an int into a string 'cs' + str(401) # Then the example works. int('401') # You can turn a string into an int too, if it's a # suitable string. int('23.2') # Error; unlike int(23.2) float('45') # Not a problem "Tigers are " + "fun" * 4 "Bwa" + "ha" * 3 - Problem: string too long "What if our string is really, really quite long and we want it to continue on the next line?" Solution: ''' try this ''' # use triple quotes == for loop over string == - we've seen "for loops" that loop through the pixels in a picture - you can loop over lots of things There just needs to be a sequence of values to go through - the "loop variable" (eg "pixel") takes on those values one at a time - the pattern for looping through a string: for char in s: - The loop variable in the example above is "char". The string being iterated over is "s". - How many times does the loop execute? ANS: the number of characters in the string == Another type of boolean expression: 's' in 'pragmatics' TRUE if one of the characters in 'pragmatics' is 's' FALSE otherwise 's' in 'hello' We can use this type of expression anywhere we can use one of the more familiar ones. if 5 == 7: if 's' in 'hello': usually, of course, we are using variables. c = 's' s = 'pragmatics' [or, the values of c and s are passed in as parameters, or from input] if c in s: ==Now we can **finally** do some interesting problem solving. That should be the focus right now. - Remember Design-Code-Verify. Explicitly state what task you want to solve, refine the explanation into pseudo-code translate the pseudo-code into code. verify the solution. - the functions '''Return the number of vowels in string s. The letter "y" is not treated as a vowel.''' def num_vowels(s): ... if __name__ == '__main__': st = "hello there" ans = num_vowels(st) print "The ans should be",4 [draw on board: st --> 'hello there' when you call: that value gets passed to s remind them: defining here, calling here ] algorithm go through the string, char by char. for each char, see if it is a vowel. if it is, increase the count so far of the number of vowels. When you are done, return the count of what you got. go through the string, char by char: for char in s: ADD for char in s: if char is a vowel: ADD for char in s: if char is a vowel: count = count + 1 What last two things are needed? [If they don't all see that they should initialize count, run that code in the python shell. we've never defined count! ] count = 0 # initialization [if we left it at that, the main program wouldn't get the result] return count def num_vowels(s): '''Return the number of vowels in string s. The letter "y" is not treated as a vowel.''' count = 0 for char in s: if char in "aAeEiIoOuU": count = count + 1 return count NEXT FUNCTION: def remove_spaces(s): '''Return s with any spaces removed.''' how could we do this? problem solving! not as obvious as the one above. There are different ways to do this. Remember: s = 'abcd' s = s + 'e' s abcde Special case: s = '' s = s + 'a' s Here's what we will do. I'll give you a hint s_no_spaces - the variable whose value we will return s_no_spaces = '' # the empty string build up the string to return in s_no_spaces return s_no_spaces ADD s_no_spaces = '' # the empty string for char in s: return s_no_spaces ADD s_no_spaces = '' # the empty string for char in s: if char is not equal to ' ': keep char; we want it in the returned value return s_no_spaces ADD s_no_spaces = '' # the empty string for char in s: if char != ' ': # or not char == ' ' keep char; we want it in the returned value return s_no_spaces ADD s_no_spaces = '' # the empty string for char in s: if char != ' ': # or not char == ' ' s_no_spaces = s_no_spaces + char return s_no_spaces done! trace it: s: 'ab cd f ' before the for-loop: s_no_spaces '' *after* the if-statment inside the for-loop s_no_spaces char 'a' a 'ab' b 'ab' ' ' 'abc' c 'abcd' d 'abcd' ' ' 'abcdf' 'f' 'abcdf' ' ' for-loop is done. s_no_spaces is 'abcdf', which is the correct value. Return it! def remove_spaces(s): '''Return s with any spaces removed.''' s_no_spaces = "" for char in s: if char != " ": s_no_spaces += char return s_no_spaces NEXT FUNCTION: def count_matches(s1, s2): '''Return the number of chars in s1 that appear in s2.''' # Note this is not symmetric. # 'e' 'ee' == 1 # 'ee' 'e' == 2 common_chars = 0 for ... return common_chars Let's think about how a human does this. s1='abcde' s2='azzcxxe' - answer is 3 'a, 'c', and 'e' are in s2 a in s2? yes +1 b in s2? no +0 c in s2? yes +1 d in s2? no +0 e in s2? yes +1 ------ 3 [if they ask, you could do it the other way around. seems more natural to me to do that.] SOOOO -- the for loop should go through -- s1! we look at each char of s1, and see if it is in s2! ADD common_chars = 0 for char in s1: return common_chars ADD common_chars = 0 for char in s1: if char in s2: common_chars = common_chars + 1 return common_chars DONE! exercise: trace this yourself def count_matches(s1, s2): '''Return the number of chars in s1 that appear in s2.''' def count_matches(s1, s2): '''Return the number of chars in s1 that appear in s2.''' common_chars = 0 for char in s1: if char in s2: common_chars += 1 return common_chars NEXT CODE (not a function - why? no particular reason) - DAY 7!