Day 4
Reading Journal Review
any_lowercase
implementation alternatives- Reactions to supplemental reading: “Holding a Program in One’s Head”
Drawing code
Visual communication is just as important in the software world as in other disciplines. The mechanism we use to describe code execution is the state diagram.
Exercise Draw a state diagram for the execution of the following code
>>> a = 1
>>> b = "Hello"
>>> a = 2
>>> b = b * a
>>> def double(n):
... res = n*2
... return res
>>> c = double(a)
Python Tutor is an excellent online tool to help you visualize code execution automatically.
Drawing the execution of your code can help you form a mental model and cement trickier concepts like:
- scope and namespaces
- functions and parameters
- (im)mutability
String Formatting
Today, you should practice the many ways that python supports formatting and manipulating strings:
- Concatenation
+
- Multiplication
*
- Slicing
[]
- String methods (e.g.
split
,upper
)
>>> excited = "Software " + "Design" + "!"*10
>>> print(excited)
Software Design!!!!!!!!!!
>>> bored = excited.rstrip("!")
>>> print(bored)
Software Design
>>> print(bored[-6:])
Design
>>> print(bored.split())
['Software', 'Design']
Python also has several other built-in facilities for formatting strings. Among other things, this makes it much easier to create things like a square root table!
There are two main ways to format strings in Python, and you’re likely to see both in code you read.
The older method uses a format string and the percent character (same as the modulo operator) to replace pieces of the format string. For example, to insert an integer, you could use:
>>> print("Your number is %d" % 52)
Your number is 52
The newer method also uses a (similar) format string, but uses an explicit format method:
>>> print("Your number is {:d}".format(52))
Your number is 52
The newer method can have a bit more complex syntax, but is often clearer and can be more powerful.
The documentation for each can be a bit dense, but fortunately there is a great cheat sheet with useful tasks at https://pyformat.info
Exercise: cheap is 33 dollars; free is 34!
You walk into a store where each item is priced according to the letters in its name: ‘a’ costs 1 dollar, ‘b’ costs 2, and so on. Write a program that prints a receipt for this wacky store:
bananas $52
rice $35
paprika $72
potato chips $78
------------------------
Total $237
What helper functions would be useful in creating this receipt program?
Hint: the built-in ‘ord’ and ‘chr’ functions may be useful. If you use these, pay attention to how case affects the result.