Lab: Python 2: Numbers

What we’re doing: More Python, this time with numbers instead of strings.

Why we’re doing it: Numbers behave differently than strings, and it’s good to understand how. You’ll also get a lot of practice defining functions and thinking algorithmically (eg how do I break this problem down into small steps?).

Preparation

Note: at the end of last class, I said we’d start this class doing the file swap thing for your chat-like functions. I changed my mind–let’s just move ahead.

Log on to a MathLAN computer and click on th Applications button in bottom left corner. Go to Development and then the program called IDLE 3. This will open a window that looks like a terminal window but running Python instead of a file directory. This is called the Shell screen. In it, you interact directly with Python.

Review & apply: 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 = day + " the weather is " + weather + "."

You also  learned about the input procedure to get data from a user. It has the following general format:

variableName = input("A prompt for the user")

This would print the contents of the prompt and return whatever the user typed as a string.

For a quick review, write a function in a new script file (in the Editor window) 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.

Try running your script. Remember, to run a script: go to File > Save and then Run > Run Module. Then call the function in the shell window, like so functionName(). 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.

In the shell, call the function 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.

Now modify your function’s output slightly to look like the following:

Enter a word: rain

Enter a second word: bow

rain + bow = rainbow.

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. 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.

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.

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

Save your script and run it. If your output reports any syntax errors, you will need to fix them.

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.

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:

print("The temperature is just " + 6 + " degrees.")

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.) Try the following example in the shell yourself to see that it works.

temperature = str(6)

print("The temperature is just " + temperature + " degrees.")

In your script file, 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!

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? Maybe we could fix that using a conditional…but right now let’s do the rest of math. Basic math, anyway.

Multiplication

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 them with int). It should also multiply the word by one of the numbers and report that result. Do you get the results you expected?

So far, we’ve defined functions with no given parameters. We can also define functions with parameters, which will use information included in the function call in the function itself. It’s clearer just to demonstrate.

This function includes two parameters:

def addNumbers(x, y)

    a = x + y

    print(a)

Now, when you call this function, you’ll include specific values for those parameters (x and y), which are called arguments.

>>>addNumbers(2,2)

4

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 in a way that would make sense to someone reading it. An example run of your program might look like this:

>>> monthMinutes(29)

A month with 29 days has 41760 minutes.

Hint: Initialize variables such as hoursPerDay, minutesPerHour, etc., before making your final numeric calculation.

Add a function imageFileSize(width,height) that computes the number of bytes required to store an (uncompressed) image and reports the result in a way that a person could read. You should assume that we need 4 bytes to store each pixel. An example run of your program might look like the following.

>>> imageFileSize(800,600)

Image width: 800 pixels

Image height: 600 pixels

File size: 1920000 bytes

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. (The term “floating-point” describes the way we represent real numbers (eg numbers with decimal places) in a computer. If we were going to have another lecture on binary representation, it would be on that, but for now, it’s enough just to know what the term refers to.)

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.

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 or in Python 3 which we are using, just 5/2). 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.

Try it out:

>>>5/2

and then

>>>5//2

See the difference? Depending on the context, one or the other of these results might be more useful.

Add a function called distributeCookies(numStudents, numCookies) that could be used by a college instructor who wants to get good course evaluations to help with the following problem. The instructor brings a batch of cookies for the class, and he must make sure that all students get the same number. Your program should then report the number of cookies each student should be given.

Save your file, run the script, and test to make sure your function works, fixing any errors.

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

>>>remainder = 5 % 2

>>>print(remainder)

So you could revise this function a little bit to make it more elegant…or just keep going.

Add a function that takes a temperature in Fahrenheit as a parameter, and reports the equivalent temperature in Celsius. The conversion equation is:

celsius = (farenheit-32) * (5/9)

An example run might look like the following

>>> convertToCelsius(100)

100 F = 37.7777777778 C

If time: making change

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:

>>> makeChange(83)

Change:

3 quarters

0 dimes

1 nickels

3 pennies

Acknowledgements

This lab is based on Jerod Weinman’s CSC 105 Python: Numbers lab.