CS61A Lab 1: Functions

Week 1, Summer 2012

Get as much done as possible, but don't panic if you don't finish.

Exercise 1: Unix/Emacs Tutorial

Do the Unix/Emacs Tutorial that can be found here: Unix/Emacs Tutorial.

Exercise 2: Command-line - Python Expressions

At your terminal, type in python as follows:

   star[200] ~ # python
Type each of the following expressions into the Python prompt >>>, ending the line with the Enter (carriage return) key. Think about what the results will be before you type them! Try to understand how Python interprets what you type. Some of these expressions will offend Python and cause it to spit out confusing error messages. In those cases, try to get the gist of what caused the error.

# this is a comment 
# do this column second 
3 
from math import sqrt, exp 
2 + 3 
exp(1) 
5 + 6 + 7 
sqrt(144) 
-16 - -16 
pi 
3 * 4 + 1 
from math import pi
3 * (4 + 1) 
pi 
from operator import mul, add 
pi * 3 
3 * 4 
print(pi) 
mul(3, 4) 
print(4) 
mul(3, add(4, 1)) 
print(add(9, 1)) 
2 ** 3 
print(print(2)) 
pow(2, 3) 
pow(pow(2, 3), abs(-2)) 

Exercise 3: Defining functions at the command-line

Recall the structure of defining a function:

def <name>(<formal parameters>):
    return <expression>

At the Python prompt >>>, type the following:

>>> def cube(n):
...     return n * n * n
...   
>>>

Be sure to indent the return statement correctly. Then, call the function cube with some numerical argument. For instance, what is 94720 cubed?

Exercise 4: Writing functions in Emacs

Now we will use Emacs, our code editor. Create a new file sumofsquares.py and type in the program below.

Do not copy and paste the following code directly. Retype it! Copying and pasting can introduce weird characters or unusual quotes, and they tend to confuse Python. (Poor Python!) Note the indentation.

# put your name here
# put your TA name here

def square(x):
    return x * x

def sum_of_squares(a, b):
    return square(a) + square(b)

Now load this program into the Python interpreter and test your function, by calling sum_of_squares with some numerical argument at the prompt.

Exercise 5: Defining your own function

Finally, we will have you write your own function! In the Emacs editor, create a distance.py file that contains the following program:

# put your name here
# put your TA name here
 
from math import sqrt, pow

def distance(x1, y1, x2, y2):
    # write your code for distance here

distance should take in two sets of x-y coordinates (x1, y1) and (x2, y2) [parameters shown above] and should compute the Euclidean distance between the two points. Use the following formula:


Load this program into the Python interpreter, and test the function by calling distance at the python prompt >>> with the appropriate arguments.

>>> distance(1, 1, 1, 2)
1.0
>>> distance(1, 3, 1, 1)
2.0
>>> distance(1, 2, 3, 4)
2.8284271247461903

Now, let us edit this program to get the distance between two 3-dimensional coordinates. Your distance function should now take six arguments and compute the following:

Reload the program, and once again test that your function does the right thing!

>>> distance(1, 1, 1, 1, 2, 1)
1.0
>>> distance(2, 3, 5, 5, 8, 3)
6.164414002968976

Exercise 6 - ucb.py Features

For this course, there are a few features that you might find useful for your assignments – the staff have provided these in a file called ucb.py, which will be provided with every project. If you would like to use the features in ucb.py, you will need to import the ucb.py file into your Python files: to do so, you should add the following statement to the top of your Python file:

from ucb import main, interact
For now, we are going to go over the main feature, which allows you to easily test your functions:

Section I: main

An entry point of a program is the place where the execution starts happening. It is usually very convenient to be able to mark an entry point in a Python file for testing purposes. Say we have the following file cube.py:

def cube(x):
    return x * x * x 

print("Should be 1:", cube(1))
print("Should be 8:", cube(2))
print("Should be 27:", cube(3))
star [123] ~ # python cube.py
Should be 1: 1
Should be 8: 8
Should be 27: 27

One problem with this file is that the tests are not cleanly arranged: it would be much better if we had a test function that performed these tests:

def cube(x):
    return x * x * x

def run_tests():
    print("Should be 1:", cube(1))
    print("Should be 8:", cube(2))
    print("Should be 27:", cube(3))

However, now, if I run the file, nothing happens:

star [123] ~ # python cube.py
star [124] ~ # 

This is because, to Python, all we have done is define two functions: cube and run_tests. We want Python to actually do something when we type in 'python cube.py'. So, we specify an entry point with the @main annotation:

def cube(x):
    return x * x * x

def run_tests():
    print("Should be 1:", cube(1))
    print("Should be 8:", cube(2))
    print("Should be 27:", cube(3))

@main
def main():
    print("Starting.")
    run_tests()
    print("Ending.")

star [123] ~ # python cube.py
Starting.
Should be 1: 1
Should be 8: 8
Should be 27: 27
Ending.

As you can see, Python will start execution at the beginning of a function with @main typed above it. The @main feature is a handy way to control what happens when you run your Python script from the command line.


For the next two exercises, you will be using Emacs. Create a file lab1.py and put the following two function definitions in this file. We will have you print this file at the end.

Exercise 7: max()

Define a procedure max(a, b) that takes in two numbers as arguments and returns the maximum of those two numbers, without using the built-in max function.

Exercise 8: expt()

Write a procedure expt(base, power) that implements the exponent function. For example, calling expt(3, 2) should return 9, and calling expt(2, 3) should return 8.

Printing:

Use the lpr command to print your lab1.py file. To do this, type the following command into your main xterm window (not Emacs or Python):

lpr lab1.py

This will print the lab1 file in the room opposite from 273 Soda. You can print other files by issuing a similar command, such as lpr my_file.txt. You have 200 free pages under your account. These pages will be handy in the coming weeks to turn in paper submissions for projects and homeworks.