Today - function call, return, start String data type

Black-box model of a function: function runs with parameters as input, returns a value. All the complexity of its code is sealed inside. Calling it is relatively simple - provide parameters, get back an answer.

(had a tech problem in lecture, now fixed)

`return`

yields the result of a functionInside the body of a function, like this:

def foo(n): ... return n * 10 ...

Suppose the caller code looks like

# in caller function a = foo(6) b = foo(7)

in out 0 0 1 10 2 20 3 30 4 40 5 60 6 72 7 84 8 96 9 108 10 120

def winnings1(score): """Compute winnings1 described above.""" if score >= 5: return score * 12 # Run gets here: we know score < 5 return score * 10

Now there's 3 cases

Move the cutoffs around a little.

Winnings2: Input score is in the range 0..10 inclusive. Bonus! if score is 10 exactly, winnings is score * 15. If score is between 4 and 9 inclusive, winnings is score * 12. if score is 3 or less, winnings is score * 10.

Now there's 3 cases; the cutoff numbers are different. Write a series of if-return to pick off the cases.

Winnings2: Input score is in the range 0..10 inclusive. Bonus! if score is 10 exactly, winnings is score * 15. If score is between 4 and 9 inclusive, winnings is score * 12. if score is 3 or less, winnings is score * 10.

Solution:

def winnings2(score): """Compute winnings2 described above.""" if score == 10: return score * 15 if score >= 4: # score <= 9 is implicit return score * 12 # All score >= 4 cases have been picked off. # so score < 4 here. return score * 10

An extra example for practice.

Lottery scratcher game: Have three icons called a, b, and c. Each is in the range 0..10 inclusive. If all three are the same, winnings is 100. Otherwise if 2 are the same, winnings is 50. Otherwise winnings is 0. Use and/or/== to make the tests.

def scratcher(a, b, c): """Return scratcher winnings described above.""" pass

Solution:

def scratcher(a, b, c): """Return scratcher winnings described above.""" # 1. All 3 the same if a == b and b == c: return 100 # 2. Pair the same (3 same picked off above) if a == b or b == c or a == c: return 50 # 3. Run gets to here, nothing matched return 0

>>> 1 + 1 # you type this 2 # Python prints this

>>> len('Hello') 5 >>> len('x') 1 >>> len('') 0

Python 012345

>>> s = 'Python' >>> s[0] 'P' >>> s[1] 'y' >>> s[4] 'o' >>> s[5] 'n' >>> s[6] IndexError: string index out of range

>>> s = 'Python' >>> s[0] # read ok 'P' >>> s[0] = 'X' # write not ok TypeError: 'str' object does not support item assignment

>>> a = 'Hello' >>> b = 'there' >>> a + b 'Hellothere' >>> a 'Hello'

>>> a = 'Hi' >>> a = a + '!' >>> a 'Hi!' >>> a = a + '!' >>> a 'Hi!!' >>> a = a + '!' >>> a 'Hi!!!'

for i in range(len(s)): # access s[i] in here

Solution code:

def doublechar(s): """Return doublechar as described above.""" result = '' for i in range(len(s)): result = result + s[i] + s[i] return result