# CS61A Lab 1: Functions

### Week 2, Fall 2012

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

### Exercise 1: Command-line - Python Expressions

At your terminal, type in python3 as follows:

`   star ~ # python3`
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 2: 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 3 cubed?

### Exercise 3: 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. Recall that we can do this by saving the file, then running python -i sumofsquares.py . Then call sum_of_squares with some numerical argument at the prompt.

### Exercise 4: 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 (using python3 -i distance.py), 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 5 - 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  ~ # python3 -i 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  ~ # python3 -i cube.py
>>>
```

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 'python3 -i 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  ~ # python3 -i 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.

A little word about -i: If you don't know already, what the -i option does is runs your Python script, then throws you into an interpreter. If you omit the -i option, Python will only run your script. Note that for the last few exercises, we didn't actually need to use the interpreter prompt, so it would have sufficed to only run python3 cube.py.

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.

Before you get started, you should know a little bit about the if statement. The basic form looks like:

```if test:
do something here
elif other_test:
do something else here
else:
do something else (else) here
```

The elif is basically 'else if' in other languages, which means if the first 'if' fails, you can try another test.

The tests need to be expressions that evaluate to boolean truth values. So for example:

```if 3 > 5:
print("Nice try!")
elif 3 > 4:
print("Try, try again!")
else:
print("There we go!")
```

That bit of code would print "There we go!". You'll see a lot more of if in the next lab, so don't worry too much about it right now. Feel free to ask your TA if you need more help!

### Exercise 6: 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 7: absolute()

Define a procedure absolute(a) that takes in one number as an argument and returns the absolute value of that number, without using the built-in abs function .

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