Introduction to Python

davidbpython.com




Project Discussion, Session 1



Please note that our first homework is due the night before our second class session. It will not be assigned until after the first class.

 
1.1 Notes typing assignment. Please write out this week's notes:

  1. In the project directory for this week, find an image named transcription_1.png.
  2. Double-click or open the image and simply type what you see displayed there.
  3. Submit your transcription (what you have typed) as the first homework assignment.
  4. This should not be in a Python program - use a simple text file, or type directly into homework submission window.

 
1.2 Tip calculator. This is a (relatively) simple calculation. Ignoring tax, the calculation is:
(bill + (bill * (tip_multiplier * .01))) / num_guests

However, keep in mind that you don't need to calculate the entire thing in one line using the formula above. You can (and probably should) break them out into separate calculations, assigning each result to a variable which you will then use in a further calculation. The values for bill, tip_multiplier and num_guests are all input through input(). Since we're doing math calcuations with these values, they all have to be converted to numeric types (int and float). So your program will take user input, convert to numeric types, convert the tip multipler value to a percentage multipler so it can be used in the formula above, and then report the result of the calculation.

 
1.3 Exponientation and tidy border.

Constructing a plan for a program, even in outline, can be a challenge at first, but this discussion will walk you through the process, so please read carefully. A program consists of a series of instructions that process data. The initial input value, an object of a particular type, will be processed through a function or operation, producing a subsequent object value, which will then be processed through another function or operation. So if you create a code outline, it will describe the process of conversion and calculation using the Python features (functions, operations and statements) that take the data through each step. Each week I will provide a link to pythonreference.com listing each of the features (function, operation or statement) we introduced this week, so you will want to have this link (as well as the links to prior sessions on pythonreference.com) available when you are designing the program. (A "feature" is simply a Python coding statement that does something, such as a function or operator statement.) Go ahead and display or print this document now as we discuss this assignment. Consider the input data and its type So, with pythonreference.com by your side, start by considering the input data -- the values the program will start with -- specifically, the input data's type and value. In this case, the program takes two inputs from keyboard using the input() function. So, what type does input() return? You'll want to be sure of this, so I suggest you refer to pythonreference.com even if you think you know the answer. Looking it up, you see that input() returns a string.

So we have two strings, which we see are expected to be made up of numeric characters, like '5' or '22'. In order to get a handle on what the program will do, you can work with a pseudocode outline. This is an outline that describes an operation, and shows the input into and output from the operation. You can outline the first two steps of your pseudocode outline this way:
str prompt -> take keyboard input -> str
str prompt -> take keyboard input -> str

This is enough to describe the two input() statements that we will need in the code.

The next thing I sometimes consider is where we're going with this -- what does the program output? At the end we're going to output the border, then the result of an exponent calculation, and then the border again:
 =======
 4782969
 =======

This doesn't tell us a lot about how to get there, but it could give us some ideas. We do know that the two inputs will be numeric digits (although they come from input() as strings) and that we will need to raise one number to the power of the other, because it's specified in the assignment. Looking at the exponent operator in pythonreference, we see that the operator uses ints or floats as inputs. So our numbers are taken from the keyboard as strings, but to use the exponent operator we must have numbers. OK then, it might be clear at that point that we need to convert these strings to ints in order to perform the exponent operation. Again referring to pythonreference, we can find and confirm that int() takes a string and returns a number based on the string value.

str prompt -> take keyboard input -> str
str prompt -> take keyboard input -> str

str -> convert to int -> int
str -> convert to int -> int

int, int -> raise one int to the power of the other -> int

If you're working with an outline, it's essential to declare the type of every statement's input and output value. Without keeping track of type, we can't know which statements can be used next. At this point the logic may be getting past our ability to visualize the outcome of each statement at one reading, so you may want to start putting in "dummy" values to do the calculation yourself. This is up to you; you may devise whatever technique you may need to keep track of what the program is planned to do.

str prompt -> take keyboard input -> str    '5'
str prompt -> take keyboard input -> str    '3'

str -> convert to int -> int                 5
str -> convert to int -> int                 3

int, int -> raise one int to the power of the other -> int  125

Now the border: how are we going to construct a border of a certain length, in the above example case a border of 3 characters? If you're not sure, look back at the tools we have available: there are 17 features listed in pythonreference for this session. Only 3 of them involve string manipulations: the concatenation operator (+), the string repetition operator (*) and the str() conversion function. Of course only the string repetition operator allows us to specify how many times a string should be repeated. You'd then have to have the "ah-ha" moment that says that if your string was a single character '=', you could specify any length you chose, as long as you had the integer value to work with:

x = '=' * 3      # '==='

I don't have any specific steps to offer for reaching this 'ah-ha' moment of using the string repetition operator in this way, but I can say that this is the point at which your puzzle-solving mind will awaken. This is where we get creative when we're solving a new kind of problem; it requires: 1. familiarity with the available tools; 2. a clear picture of the data we're working with (type and (sample) value); 3. a clear picture of how the data should look by the end (type and value); 4. a willingness to speculate on how we might get there using available tools. This is basically what programming Python is about: a data problem that requires a formula for transforming the data through various steps using available tools/features. Of course we're not quite there yet. As we can see from the sample program runs, we can't specify 3 in our code, because the border needs to match whatever the result of the exponientiation is, and that is dependent on the user's input during that program run:

Sample program run:
 please enter an integer:  3
 please enter another integer:  14
 =======
 4782969
 =======
 please enter an integer:  3
 please enter another integer:  5
 ===
 243
 ===

So then our last question is how we can derive the # of digits of an integer, because that's the "length" our integer should be. Our first thought would probably be to use len() since it tells us the length of things. Unfortunately, double-checking pythonreference we see that len() gets us the length of strings, not ints. We might then ask whether it's possible with an int anyway, and you could even try creating a .py file in PyCharm and testing it out:

x = 55

y = len(x)      # TypeError:  object of type 'int' has no len()

print(y)

So unfortunately our (totally reasonable, but unsuccessful) test shows that you can't just get the len() of an int. And our review of len() in pythonreference shows that you can only get the len() of a string. So, one last connection is needed: if we want to get the "len" of an integer and len() takes a string, we can simply convert the integer to a string and get the len of that. So now we're clear to complete our outline, with data visualization added:

str prompt -> take keyboard input -> str          '5'
str prompt -> take keyboard input -> str          '3'

str -> convert to int -> int                       5
str -> convert to int -> int                       3

int, int -> raise one int to the power of the other -> int  125

int -> conver to str -> str                     '125'

str -> get length -> int                           3

int 3, str '=' -> repeat string 3 times -> str  '==='

print str                                       '==='

print int                                        125

print str                                       '==='
 
1.4 Price per unit comparison.

It would make the most sense to use float() to convert all four inputs (the unit sizes and price per unit) to numbers for calculation. After the simple math calculations, use round() to convert the calculated values to floats with 2 decimal places.

 
1.5 Share calculator.

The input for cash to invest must of course be converted to an float(), and since the number of shares must be a whole number, you'll want to round down -- use int() for this purpose.

If you're having problems with the get_price() function you can of course check to see if your internet connection is active, however for the purposes of this assignment you don't need this function -- you can simply hard-code a float price that you can use for testing.
cc = 100.50   # sample share price for testing purposes

Please note that in order to run this code you will need to install a 3rd party module: requests.

  • open a Terminal window (Mac) or Command Prompt window (Windows)
  • at the prompt, type pip3 install requests (Mac) or pip install requests (Windows)
  • when output is complete, take a look at it and scroll up a bit; it should indicate success (or at least, not failure)
  • any issues, please get in touch

 
[pr]