This activity will introduce one of the true “core concepts” of computer science: the idea of data types. Every piece of data in a computer is stored as a collection of binary bits: ones and zeros. In order for the computer to manipulate data correctly, it is crucial that it keep track of what type the data is, so that it can correctly interpret the binary bits. When programming, it is also essential to pay close attention to data types.
In this activity, you will look at several simple built-in types of data in Python. First you will learn about numbers, which may be separated into integers and floating-point (real) numbers. Then you will explore strings, which allow us to represent text data. And finally you will learn about lists, which store collections of other data.
To hand in: You will use Github Assignment to set up this assignment, and to push your code to save it to the cloud, to hand it in.
Numbers
Python has two main kinds of numbers: integers, and real, or floating point, numbers (There are other kinds of numbers, as well, but we probably won’t use any of them). The official names for these types are int and float. Table 1 shows basic numeric operations and functions. Many more common mathematical operations are in the math module, which you can add in when you need it.
Table 1: Basic built-in arithmetic operations, and functions on numbers
Example
Meaning
3 + 12
Adds two numbers, returning the result
45 - 19
Subtracts second from first, returning the result
5 * 100
Multiplies two numbers, returning the result
55.0 / 2
Divides first by the second, returning the result as a float
55 // 2
Divides first by the second, returning the quotient portion as an int
30 % 4
Computes the remainder of first divided by second
2 ** 3
Raises first to the power of the second
max(1, 5, 3)
A function that returns the largest of values passed to it
min(1, 5, 3)
A function that returns the smallest of values passed to it
abs(-3)
A function that returns the absolute value of its argument
round(3.2)
A function that rounds its argument
int(3.2)
Converts its argument to an integer
float(2)
Converts its argument to a floating-point number
Integers and floats are treated as different, though related, kinds of data. This is why we have explicit operators to convert from one type to the other.
In general, arithmetic operators follow this rule: If both operands are integers, then the result is an integer. If at least one operand is a floating-point number, then the result is a float, too. The single-slash, decimal division operator is an exception: it always returns a float.
There are three division-related operators: decimal division (/), quotient division (//), and remainder (`%). Decimal division gives the normal calculator result for dividing two numbers. Quotient division returns only the integer part, the quotient of the division. It cuts off any part after the decimal point (another way of thinking about it is that it takes the floor, it rounds down to the nearest integer less than the value). The remainder operator gives the remainder of the division of its two operands.
Examine the code below, which runs each of the examples above and prints their results, along with explanatory text. Can you correctly predict each result?
Create a new Python file in your project for this activity, and try copying this code and running it. Do you get the same results? Experiment with changing the values, especially changing int to float and vice versa, and examining the results. Ask questions if you aren’t sure what is happening here, or why you are getting a particular result.
Try this to hand in: Suppose you have a banana that is 15.5 cm long. If you had 5,100 such bananas, how many meters would they cover, laid end to end? Create a new Python file and put your answer in the file. Start with a Python statement to define variables bananaLength and a variable numBananas, and then create a statement that computes how long they would be, in meters. Make sure to print the final result, including units and explanatory text.
Strings
Strings are collections of characters, and characters are keyboard symbols; each character represents a single keyboard key. Strings allow us to incorporate text into our programs, making them more readable. Programs can also perform text processing, though we will get to that later on.
Strings and characters are written the same in Python. A character is just a string of length 1. Strings are written with quotes before and after them. You can either use double-quotes (") or single-quotes ('), as the examples below show. You can also make triple-quoted strings that use three single-quotes or three double-quotes. Triple-quoted strings are the only ones that can be written over multiple lines, and we use them for program documentation as well.
Below is a script that demonstrates various ways of writing strings, and printing their values.
print('Hi there')print("Hi there")print("I contain an apostrophe, don't I?")print('I was told, "Double quotes go inside single quotes!"')s1 ="cat"s2 ="dog"s3 ='hi mom'longStr ="""As I was going to St. Ives,I met a man with seven wives.Each wife had seven sacks,Each sack had seven cats,Each cat had seven kits.Kits, cats, sacks, and wives:How many were going to St. Ives?"""print(s1, s2, s3)print(longStr)
Hi there
Hi there
I contain an apostrophe, don't I?
I was told, "Double quotes go inside single quotes!"
cat dog hi mom
As I was going to St. Ives,
I met a man with seven wives.
Each wife had seven sacks,
Each sack had seven cats,
Each cat had seven kits.
Kits, cats, sacks, and wives:
How many were going to St. Ives?
Copy the script above to a test file in PyCharm, and experiment with it. What happens if you don’t match quotation marks, or you put a line break in a string that isn’t triple-quoted?
The table below lists basic string operations. With these we can pull strings apart and put them together again, check their size, and ask about substrings within the larger string. When we concatenate two or more strings, we put them together as one big string. We slice a string when we extract a particular substring, based on its indices.
Strings are indexed starting with 0 at the left end, and increasing as you go right. We can also use negative numbers to index characters from the right end going left (see Table 2 to see how to index the example string "AB CD")
Table 2: Indices to reference individual characters in the string "AB CD!"
A
B
C
D
!
positive indices:
0
1
2
3
4
5
negative indices:
-6
-5
-4
-3
-2
-1
Add the script below to the script from earlier. You need the variable definitions for this to work.
len returns the number of characters in its argument
2
+ concatenates strings together
3
* concatenates a string with itself N times (N * s or s * N)
4
in checks if the first string occurs in the second string
5
Accessing with [n] returns the character at position n
6
Slicing with [s:e:j] returns the substring fromsup toe, skipping byj`
3 3 198
catfish abc
XXXXXXXXXX dogdogdog
True True False
c m g
at do mo man
Experiment with this script, changing which strings, positions, substrings are included. Ask questions if any result or operation does not make sense to you.
Try this to hand in: Make a new Python file, and write a program as described below to automate the writing of a thank-you note.
First, define a variable with the name of the person who has given you a gift.
kindPerson ='Aunt Judi'
Build a second variable that holds your thank-you note, using the + operator so that instead of including a specific gift-giver’s name, you insert the variable kindPerson. Print the final string, which should look like:
Dear Aunt Judi,
Thank you for the graduation present. I can’t wait to use it. I
hope you are enjoying your summer. You’re the best, Aunt Judi!
Love, Mittens
Lists
A list is a linear collection of data. That means that it is a container that holds multiple pieces of data, lining them up in some kind of order. In Python, lists can hold any type of data, including other lists, with varying data types even within a single list.
You write a list by surrounding the data with square brackets. Both lists and strings share some of the same operations; see the examples below.
A note about slicing: Slicing is an incredibly versatile operation. We can use it to select a sequential sublist, or to pull out every 3rd element, or other similar patterns. If we want to start or end at an end of the string, we can leave out the value on that side of the colon (:).
Copy this script into a new file in your activity project. Look closely at each operation, and its result. Experiment with changing the numbers in the slicing, adding numbers where they are missing, or removing them. Ask questions if any operation or result is confusing to you.
Try this to hand in: Create a script that starts by defining a variable to hold a list of 6 numbers. From the list, pull out three values, at positions 0, 2, and 4 (use the square bracket access operator). Using arithmetic operators, add the three values together, and assign the result to the variable evenSum. This can be done in one line of Python, it you are careful. In another variable, oddSum, calculate the sum of the numbers at positions 1, 3, and 5. Print these two results. Make sure your script works correctly and prints the correct sums of odd and even values, even if you change the values in the original list!
Optional Challenge Question for Those Who Get This Far
Consider the problem of making change: figuring out how many bills and coins to give someone to make a specific amount of money. This example asks you to make a script to solve this problem. You might start by discussing this question with a neighbor, and developing together your ideas for how to solve the problem, in English or pseudocode. The key idea to making change is to take the quotient and remainder of an amount by the next monetary unit.
Consider an example. If we start with $7.32, for simplicity (and to avoid floating-point numbers) we will represent it as 732 cents. If we take the quotient of 732 by 100 (for one dollar bills), then we get 7, and the remainder of 732 divided by 100 is 32. That means 32 cents is the part left over after paying 7 dollar bills. Then using the left over 32, repeat for the next coin: quarters. Divide 32 by 25, and get 1, and the remainder is 7 cents. Continue in this manner.
Now, see if you can write a Python script, a series of expressions or statements in Python, that do this calculation and print out the results. Open a new Python file, Define a variable, money, that contains a money amount in cents (like 732 for $7.32, for example).
Then, create a series of Python statements that calculate and print how to give change for the money value, in dollars, quarters, dimes, nickels, and pennies. The best solution will use integer division and the remainder operation.
Below is an example of what might print when this script is run:
Making change for 732 cents:
Dollars: 7
Quarters: 1
Dimes: 0
Nickels: 1
Pennies: 2
Once you get the script working for 732, change the value of money and test your script on other values to be sure it works more generally.
What to hand in
You should have multiple Python files for this activity. You might have files containing the example scripts for each data type, along with your experiments. At the very least, you must have:
A file containing your solution for the banana problem
A file containing the thank you note script
A file containing the odd-even list addition problem
(Optional: the script for the change-making challenge question
Use commit and push to copy your code to Github to submit this work.