Python Numbers

CSC 105 - The Digital Age - Weinman



Summary:
In this laboratory, you continue the journey and joy of learning to write computer programs in the Python programming language.

A. Preparation

  1. Open a terminal window and launch the Calico program by typing (or pasting) the following command
    /opt/Calico/calico &
  2. In the Calico window that opens, click the Shell tab. You should see a blank white window with a python> prompt and a blinking cursor.
  3. In the tab titled "New Python Script", enter comments (lines beginning with # for you and your partners names, and the title of this lab).
  4. Save the file in your 105 folder as numbersLab.py

B. Addition with Strings

In the last lab, you worked with character strings and found that the plus sign can be used to concatenate two strings together, as in the following
sentence = partner1 + " and " + partner2 + " control this computer."
In today's reading, you learned about the input procedure to get data from a user. It has the following general format:
<variable name> = input(<some prompt string>)
This would print the contents of the prompt and return whatever the user typed as a string. (The reading also talks about how to convert this string to numbers, which we'll practice in the next exercise.)
The reading also showed you how to print a value to the screen using the following general form
print(<some output string>)
  1. For a quick review, write a function in your script file called wordCat that takes no parameters, asks the user to enter two words, and then prints the words concatenated together. An example run of your program might look like this:
    Enter a word: rain 
    Enter a second word: bow 
    The compound word is rainbow.
    1. Try running your script.
      If you see errors printed in the Output, note the line numbers and see if you can find and fix them. If not, be sure to ask the instructor or mentor for assistance.
    2. In the Shell, type the command wordCat to test your program to make sure it behaves as expected. If it does not, you'll need to repeat these steps to save, fix, run,and test.
  2. Now modify your function's output slightly to look like the following:
    Enter a word: rain 
    Enter a second word: bow 
    rain + bow = rainbow.
  3. Try entering numbers (such as 5, not five) into your program when it asks you to enter words. Does the result make sense for numbers?
Not really. Most of us would prefer the plus sign to add two numbers rather than appending them together. Luckily, Python can do this too.
The issue here is that Python (like other programming languages) makes a distinction between numbers and strings of characters that contain numeric digits. To see the difference, think of your zip code. It makes no sense to add or multiply zip codes; thus, a zip code isn't really a number, it is really a character string that happens to contain numeric digits. Indeed, many countries use postal codes that include both alphabetic characters and numeric digits.
But how is Python to know when you enter numeric digits at the keyboard whether your intent is a number or a string containing numeric digits? Python cannot know this on its own, so you (the programmer) needs to specify. In the next exercise, you will learn how to do this.

C. Addition with Numbers

As you learned, function input returns a character string. So the code statement
numberAsString = input(Enter a number: )
will load a character string containing numeric digits into the aptly named variable numberAsString. We can then convert the character string into an integer with a function called int() as follows:
numberValue = int(numberAsString)
After this line of code is executed, numberAsString still contains a string of digits, but numberValue contains the number entered specifically, an integer.
Recall that the digit 5 would be stored in ASCII with the bits 0110101, because it has the code number 53. However, the numerical representation of the digit in binary is 0000101. It is therefore important to consider the type of the underlying data because integers and characters are stored differently in the computer.
  1. Using this strategy, add the function addition() to your script that prompts the user to enter two numbers, converts the string input values to integers, adds them, and reports the result. Note that using the + operation on integer types does the obvious thing; adding the numbers rather than concatenating them.
    An example run of your program might look like this:
    Enter a number: 4 
    Enter a second number: 78 
    82
    1. Save your script and run it. If your Output reports any syntax errors, you will need to fix them.
    2. Be sure to run your function by typing addition() in the shell more than once, entering different integers each time. It should compute the correct sum, regardless of which integers you enter.
  2. Now you have added numbers and concatenated strings, both using the + operator. What do you suppose happens if we try to add a string and a number? Type the following command in the Shell to find out (with apologies to Weird Al Yankovic).
    print("This song is just " + 6 + " words long.")
    You got an error message, right? The best we might hope for in this situation is for the number to be concatenated with the strings. However, again because numbers are inherently different types than strings, Python cannot do this. Yet, as the example suggests, there are times when we would like to do so.
  3. In such a situation, we can use a function called str to convert the number to a string containing the same digits. (Thus, the function str is essentially the inverse of the function int, which you just learned.) Try the following example in the Shell yourself to see that it works.
    songLength = str(6)
    print("This song is just " + songLength + " words long.")
  4. Write a simple function called graduate() that asks the user to enter the year he/she/zi expects to graduate. Then print a message that includes this information. An example run of your program might look similar to the following.
    What year will you graduate? 2016 
    You will graduate in 2016? Congratulations!
  5. Now see if you can modify your function graduate, so that its output message is like the following.
    What year will you graduate? 2016 
    Congratulations! You have only 1 more year to go!
    Note that to do so, you will need to subtract two numbers, which can be done just as you would probably expect. Don't forget to use int for conversion before doing any arithmetic!
    Finally, try entering different years when you run this function. Does it work correctly for any given year 2015 or later? If not, please modify your function so that it does.

D. Multiplication

  1. The multiplication operator in Python (and other programming languages) is an asterisk. For example, we might say
    product = 2 * 3
    Add a function called multiply() that asks the user to enter two numbers (don't forget to convert these with int) and a word. Your program should then multiply the two numbers together and report the result (don't forget to convert it with str). It should also multiply the word by one of the numbers and report that result. Do you get the results you expected?
  2. Add a function called monthMinutes(numDays) takes in the number of days in a given month. Your program should then compute the number of minutes in the month, and report the result. An example run of your program might look like this:
    python> monthMinutes(29)
    A month with 29 days has 41760 minutes.
    Hint: Initialize variables such as hoursPerDay, minutesPerHour, etc., before making your final numeric calculation.
  3. Add a function imageFileSize(width,height) that computes the number of bytes required to store an (uncompressed) image. You should assume that we need 4 bytes to store each pixel. An example run of your program might look like the following.
    python> imageFileSize(800,600)
    Image width: 800 pixels 
    Image height: 600 pixels 
    File size: 1920000 bytes

E. Division

The only numbers we have used in the examples so far have been integers, but we can work with floating-point numbers in Python as well. (Remember that the term "floating-point" describes the way we represent real numbers in a computer.)
Why should we care? One reason is that division can give a different result when we divide two real numbers than when we divide two integers. For example, the result from the integer division (5 // 2) will differ from the result given by (5.0 / 2.0). This may seem surprising at first, but consider that it is similar to the fact that the addition operator gives a different result when we add two numbers than it does when we add two strings. It is a way to make both of these useful operations available to you, the programmer.
  1. Add a function called distributeCandy(numStudents, numPieces) that could be used by a kindergarten teacher to help with the following problem. The teacher brings a bag of candy for the class, and he must make sure that all students get the same number of pieces. Your program should then report the number of pieces each student should be given.
    1. Save your file, run the script, and test to make sure your function works, fixing any errors.
    2. Once you have that working, modify the program so that it also prints the number of pieces that will be left over for the teacher.
    3. Once you have the second part working as well, you may or may not be pleased to learn that there is another operator you can use to compute the remainder in an integer division problem. For example, the commands below should compute and print the remainder after removing as many 2's as possible from 5.
      remainder = 5 % 2
      print(remainder)
  2. Add a function that takes a temperature in Fahrenheit as a parameter, and reports the equivalent temperature in Celsius. The conversion equation is:
    celsius=(fahrenheit-32.0)× 5.0

    9.0
    An example run might look like the following
    python> convertToCelsius(100)
    100 F = 37.7777777778 C

F. For those with extra time

Consider how store clerks give change to their customers. To be considerate, they always try to give the exact change using the fewest coins possible. It turns out that this can always be done (in U.S. currency) by giving as many quarters as possible, followed by as many dimes as possible, and so on down to pennies.
Add a function called makeChange(cents) that takes the amount of change your program is to make, and then compute the number of quarters, dimes, nickels, and pennies that produces the correct change with the fewest coins possible.
A sample run of your program might look something like this:
python> makeChange(83) 
Change: 
  3 quarters 
  0 dimes 
  1 nickels 
  3 pennies
This derivative work was originally authored by Marge Coahran.
Copyright © 2015 Jerod Weinman.
cc-by-nc-sa.png This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 4.0 International License.