![]() |
![]() |
|
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
Yesterday, we walked through
examples of using
// Return the RU Username, except check for Jay Z who gets a special honorific. // def ruUserName( firstName, lastName ): if firstName == "Jay" and lastName = "Z": return "hisroyalflyness" else: firstInit = substring(firstname,0,1) return string.lower( firstInit + lastName ) |
// Charge $4.95 for shipping, unless the order is worth more than $100 total, // or it has more than 50 items (in which case shipping is free). // def shippingCharge( numItems, unitPrice ): if (numItems*unitPrice > 100 or numItems > 50): return 0.00 else: return 4.95 |
The precise semantics for
|
TASKS: we will check off the following two items:
# substring : string, int, int → string # Given some text, a start-index, and a stop-index, # return the characters of `txt` from `start` up until (but not including) `stop`. # Indices are 0-based. # Examples: substring( "radford", 3, 6) = "for" # substring( "radford", 0, 3) = "rad" # def substring(txt, start, stop): if (0 <= start and start <= stop and stop <= len(txt)): return txt[start:stop] else: raise IndexError("substring: bounds out of range: " + str(start) + "," + str(stop) + " for '" + txt + "'") |
Self-challenge (not to be checked off, at least not today):
in
Update
(Be sure to include
Further self-challenge: Handle the case where somebody doesn't have a first name (in which case the empty-string will be passed in2).
1If you replace
2 Technically, I'd split hairs over the distinction of "not having a first name" vs. "having a first name which is zero letters long". Granted, this isn't actually a distinction with people's names, but consider the situation where you look up a (last)name in a database: there is a difference between Sting not being in the database, vs. Sting being there but not having a last name.
A full programmer might say that “no last name” is represented by
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
©2014, Ian Barland, Radford University Last modified 2014.Apr.21 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |