2016 September 29,

CS 111: Supplementary Tutorial

Thus far in our course we have seen five basic types of data: floating-point numbers, integers, Booleans, strings, and lists. This tutorial reviews their basic capabilities. Refer back to earlier tutorials for more detail.

Whenever you write computer code, it is essential that you know the type of each object in your code. Why? Because the type determines what that object can do. If you don't know the object's type, then you can't use the object effectively.

Floating-point numbers

Here are the basic arithmetic operations on floating-point numbers: +, *, -, /, **. If you want fancier mathematics, such as cosines and logarithms, then import the math module and use math.cos, math.log, etc. Try these example commands.

3.0 ** 4.0
import math
x = math.log(100.7)
x
math.sin(math.pi / 2.0)
type(math.sin(math.pi / 2.0))

A complicated mathematical expression may contain many nested parentheses. When evaluating such an expression, we always work from the inside out — from the deepest part of the nest to the shallower parts. In the last example above, Python first evaluates math.pi and 2.0, then divides them to get 1.5707963267948966, then takes the sine of that number to get 1.0, then determines what the type of 1.0 is.

Integers

Computers store integers (whole numbers) differently from floating-point numbers. The same basic arithmetic operations work on integers: +, *, -, /, **. In particular, the / operator produces a floating-point number, even when acting on two integers that have an integer quotient.

18 / 7
18 / 6

Because division of integers doesn't produce integers, Python supplies two more division operators for integers: // (the integer part of the quotient) and % (the remainder).

18 // 7
18 % 7

Whenever you do an arithmetic operation on a mixture of integers and floating-point numbers, the integers are automatically converted to floating-point, and the floating-point arithmetic proceeds from there. For example, 2 * 7.1 is converted to 2.0 * 7.1, which evaluates to 14.2.

Booleans

Booleans are quantities that are either True or False. Frequently they arise from comparisons of other objects using operators such as ==, !=, >, <, >=, <=. The basic operations on Booleans are and, or, and not.

13 == 26 / 2
17 != 17.0
x = 7
x == 7
x < 5 * x + 3
x > 4 and x < 5 * x + 3
y = 6
y == x or 2 * y == x
not (y == x or 2 * y == x)

Booleans are mainly used in if statements and while loops. An if statement tests whether the given Boolean is True or False. If the Boolean is True, then the subsequent block of code is executed. If the Boolean is False, then the else block is executed instead. The else block is optional.

if x > 10:
    print("This x is big.")
if x > 10:
    print("This x is big.")
else:
    print("This x is small.")

You can also nest one if statement inside another. You can also chain if statements together using elif.

if x > 10:
    print("This x is big.")
else:
    if x < 5:
        print("This x is really small.")
    else:
        print("This x is small, but not really small.")
if x > 10:
    print("This x is big.")
elif x < 5:
    print("This x is really small.")
else:
    print("This x is small, but not really small.")

A while loop is similar to an if statement, except that the block gets executed repeatedly until the Boolean is False. (Also, there cannot be an else block.)

i = 0
while i < 10:
    print(i)
    i = i + 2

Python is sensitive to indentations. Within a single block, every line must be indented in exactly the same way.

Lists

A list is a sequence of zero or more objects of any type. You enter a list into Python using square brackets:

l = [13.2, 3, -7, 1.0]
l

Lists have operators + and len for concatenation and length. The items in a list are indexed 0, 1, 2, and so on, up to one less than the length of the list. You can access the items by their indices using the [] operator.

otherList = [4, 1]
l + otherList
otherList + l
len(l)
l[2]
l[3] = otherList[0]
l
otherList

The elements in a list can be any kind of Python object, including other lists. A list of lists is often a good way to represent a table or grid, including a Tic Tac Toe board.

l = [[9, 8, l], [11, -3], 2]
l
l[0]
l[1]
l[2]
l[0][2]
b = [["X", " ", "O"], [" ", " ", "X"], ["O", " ", " "]]
b
b[0]
b[0][2]

Another way to make a list is the range function. This function makes only one special kind of list: an arithmetic sequence of integers. These arithmetic sequences are surprisingly common in programming, so range is worth knowing about. The range function takes in three integers, and counts from the first integer, to just before the second integer, using the third integer as a step size. If the third integer is missing, then it is assumed to be 1. If the first integer is missing, then it is assumed to be 0.

list(range(3, 19, 4))
list(range(3, 19, 2))
list(range(3, 19, 1))
list(range(3, 19))
list(range(0, 19))
list(range(19))

For technical reasons, Python refuses to show you the contents of a range-created list unless you explicitly precede it with list. So that's what we did in the examples above. But usually when we use range we'll omit the list part.

It is extremely common to want to perform some calculation on each item in a list. You can accomplish this using a while loop, but frequently a for loop is more convenient.

i = 0
while i < len(l):
    print(l[i])
    i += 1
for i in range(len(l)):
    print(l[i])
for item in l:
    print(item)

What a for loop does is very simple. Every for loop over a list begins with a line of the form

for VARIABLE in LIST:

followed by an indented loop body. The body executes once and only once for each item in the list.

You can name the variable whatever you want (although some names are more understandable than others). Usually we use names such as i, j, and k for integers. If the elements in the list are of some other type, then we might use a more descriptive name.

Strings

A string is a sequence of zero or more characters. In other words, a character is a string of length one. You enter a string using single or double quotation marks:

s = "computer science"
s
string = 'is the study of algorithms'
string

Like lists, strings support operators + and len for concatenation and length. You can access the characters using their indices and the [] operator. However, Python strings are immutable, so you cannot change a character in a string using the [] operator.

s + string
string + s
s + ' ' + string
string[3]
string[3] = 'G' # an error will happen here

You can loop over strings in exactly the same ways that you loop over lists.

i = 0
while i < len(s):
    print(s[i])
    i += 1
for i in range(len(s)):
    print(s[i])
for char in s:
    print(char)

A list of characters is similar to, but not exactly the same thing, as a string. Usually, if every item in your list is a character, then you should be using a string instead. (But we violate that advice in our Tic Tac Toe assignment.)

s = "computer science"
l = ['c', 'o', 'm', 'p', 'u', 't', 'e', 'r', ' ', 's', 'c', 'i', 'e', 'n', 'c', 'e']
s[0]
l[0]
s == l
l[3] = 'G'
l
s[3] = 'G'

Questions

Question A: What does the following code print?

x = 9 // 2
y = [x]
z = 'y'
print(x, type(x), type(y), type(z), type('z'))

Question B: In the following expression, what is the type of each subexpression? In other words, track how the type changes (if it does) as you work your way from the inside out.

math.sin((9 + 3) / 2)

Question C: In the following code, what type of values does the variable i take on? Is i a good name for this variable?

name = 'LeBron James'
for i in name:
    x = i

Question D: What does the following code print?

pos = [2, 1]
myList = [11, 24, [33, 10, [19, 17]], [14, 26], [[22, [31]]]]
print(type(pos), myList[3], type(myList[2]), myList[pos[0]], myList[pos[0]][pos[1]])

Question E: Referring back to the previous question, explain how you could use the [] operator multiple times on myList to get the 31 out?

Question F: Suppose that the variable x contains an integer value. Write a little code to test whether that integer is divisible by 5.

Question G: Write code to find the smallest positive integer that is divisible by both 12 and 15.

Question H: Suppose that the variable x contains a string value. Write code to count how many occurrences of the letter C are in that string, counting both lower- and upper-case Cs.