Laboratory: Programming in Python (Numbers)
CSC 105 - The Digital Age

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

Contents

Exercise 0: Preparation

Open a terminal window, and move to the code directory you created in the first Python lab:

   cd 105/code

Next, open the text editor gedit as shown below, and then arrange your windows so that you can see the terminal window and gedit at the same time.

   gedit &

Remember that you will move back and forth between these two windows as you did last time:

Next, please quickly review the previous lab so that the lessons you learned there will be fresh in your mind for you to use today.

Exercise 1: Addition in Python

a. In the last lab, you worked with strings and found that the plus sign can be used to concatenate two strings together. For a quick review, write a program that 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.

Now modify your output to look like the following.

Enter a word: rain
Enter a second word: bow
rain + bow = rainbow.

b. 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 need to specify. In this exercise and the next, you will see two different ways to do this.

First, it turns out that the function raw_input always returns a character string. So the code statement

data = raw_input("Enter a number: ")
will load a character string containing numeric digits into the variable data. We can then convert the character string into an integer with a function called int() as follows:
num = int(data)
After this line of code is executed, data still contains a string of digits, but num contains a number – 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.

c. Using this strategy, write a program called addition.py 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

Be sure to run your program more than once, entering different integers each time. It should compute the correct sum, regardless of which integers you enter.

d. An alternative way to handle this situation would be to use a different function to read input from the user. While raw_input() always returns a string of characters, there is a similar function called input() that always returns a number. Thus, if you use the statement below, the value in the variable number can be added to other numbers as is (with no need to convert it to an integer first).

number = input("Please enter a number: ")

Now write a program that uses input() to accept two numbers from the user, then adds them together and reports the result.

e. 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? Try the following short program to see.

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.

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.) Please try the following example yourself to see that it works.

songLength = str(6)
print "This song is just " + songLength + " words long."

f. Write a program called graduate.py that asks the user to enter the year he or she expects to graduate. Then print a message that includes this information. (Your program should use input() to accept the input data, so that you can exercise your knowledge of the function str.) An example run of your program might look similar to the following.

What year will you graduate? 2015
You will graduate in 2015? Congratulations!

g. Now see if you can modify your program graduate.py, so that its output message is like the following. Note that to do so, you will need to subtract two numbers, which can be done just as you would probably expect.

What year will you graduate? 2015
Congratulations! You have only 1 more year to go!

Finally, try entering different years when you run this program. Does it work correctly for any year on or after 2014? If not, please modify your program so that it does.

Exercise 2: Multiplication

a. The multiplication operator in Python (and other programming languages) is an asterisk. For example, we might say

product = 2 * 3

Write a program that asks the user to enter two numbers and a word. Your program should then multiply the two numbers together and report the result. It should also multiply the word by one of the numbers and report that result. Do you get the results you expected?

b. Write a program that asks the user to think of a month and then enter the number of days in that 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:

How many days are there in your month? 29
Your month has 41760 minutes.
(Hint: Start by thinking about how many hours there would be in the month.)

c. In this exercise, you will write a program called imagesize.py that computes the number of bytes required to store an (uncompressed) image. You should assume that we need 4 bytes to store each pixel, and you should ask the user for the width and height of the image (in pixels). An example run of your program might look like the following.

Image width (pixels): 800
Image height (pixels): 600
File size: 1920000 bytes

Exercise 3: Division

a. 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.) We use the function input to accept floating-point numbers from a user, just as with integers. Python will recognize a number as a floating-point number if it contains a decimal point; otherwise, the number will be recognized as an integer.

For example, if the user chooses to answer the prompts in the following way, Python will consider the first number an integer and the second one a floating-point number.

Please enter a number: 5
Now another number: 5.0

Why should we care? One reason is that the division operator gives a different result when we divide two real numbers than it does when we divide two integers. For example, the result from (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.

Write a program that accepts two numbers from the user, then divides the first one by the second one and reports the result. Then experiment by running your program and entering different numbers. Try to determine the answers to the following questions:

We call the operation of dividing two integers integer division. If you are still not completely sure what it does, here is a hint. I know a Prof who claims we learned it in elementary school as the "gazinta" operator: it tells us how many times one number goes into another (evenly). So ( 5 / 2 ) can be restated as "2 goes into 5 two times."

b. In this exercise, you will write a program called candy.py 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 prompt the teacher to enter the number of students who are present that day, and also to enter the number of candy pieces available. Your program should then report the number of pieces each student should be given.

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.

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 program below should compute and print the remainder after removing as many 2's as possible from 5.

remainder = 5 % 2
print remainder

Unless you used this operator already, modify your program to use it when computing the amount of candy left over for the teacher.

c. Return to your program called imagesize.py. Modify it so that after printing the number of bytes needed to store the image, it also reports the number of kilobytes needed.

Hint: Remember that one kilobyte is equal to 1024 bytes, so you want to divide the number of bytes by 1024.

An example run of your program might look like the following:

Image width (in pixels): 800
Image height (in pixels): 600
File size: 1920000 bytes
That is: 1875 kilobytes

d. Write a program that prompts the user to enter a temperature in Fahrenheit, and reports the equivalent temperature in Celsius. The conversion equation is:

celsius = (fahrenheit - 32.0) * 5.0 / 9.0

A sample run should give you the following result:

Enter degrees fahrenheit: 100
Celcius degrees:  37.7777777778

Exercise 4: 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.

Write a program called change.py that asks the user to input 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:

Enter the total change: 83
Change:
  3 quarters
  0 dimes
  1 nickels
  3 pennies
Written: Marge M. Coahran, February 2008
Revised: Jerod Weinman, 2 January 2009
Revised: Jerod Weinman, 25 February 2011
Revised: Jerod Weinman, 22 February 2014
Adopted from: CSC105: Programming in Python (Numbers)
Copyright © 2009-2014 Marge Coahran and Jerod Weinman.
CC-BY-NC-SA This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License .