CS111 Lecture: Functions

In this notebook there are the following topics/activities:

1. Defining your own funcions
2. Multiple parameters
3. Excercise 1: write your own function average
4. Functions That Call Other Functions
5. Zero-parameter functions
6. return vs. print
7. Drills: Writing Functions
8. Functions with side effect and no return value
9. Exercise 2: Incremental Development of Functions with Number Statistics
10. Exercise 3: Old Macdonald has a farm
11. Functions with Graphics
12. Exercise 4: Colorful Stars
13. Exercise 5: drawRectangle
14. Exercise 6: drawSquare
15. Fish Tank
16. Fruitful Graphics
17. Exercise 7: Fruitful Square
18. Practice Writing Functions

1. Defining your own functions

Functions are a way of abstracting over computational processes by capturing common patterns. You have already used built-in functions like len, max, input and many more. Here is a user-defined function to compute the square of a number.

Calling or invoking the function: we can call a function many times, but we define it once.


A parameter names "holes" in the body that will be filled in with the argument value for each invocation.

The particular name we use for a parameter is irrelevant, as long as we use the name consistently in the body.

The following function call will generate the same result as the one from the definition of the function with a different parameter name.

2. Multiple parameters

A function can take as many parameters as needed. They are listed one by one separated by comma.

Important: The order of parameters specifies the order of argument values.

Problem description: A 1 kg brick falls off a high roof. It reaches the ground with a velocity of 8.85 m·s-1. What is the kinetic energy of the brick when it reaches the ground?

Call the function:

You are given the following simple graph that depicts two points A and B in the 2-D coordinate system, where every tick is a unit of 1. Call the functioon distanceBetweenPoints with the right values to calculate the distance.

Call the function:

3. Exercise 1: Write your function: average

Define a function named average that takes two numbers and returns the average of the two.

Now try calling your function as below:

4. Functions That Call Other Functions

When defining your functions, you can call other functions within the body of your definition.

We can also call our own user-defined functions like the function square above. Make sure that square above is defined before you try and invoke hypotenuse.

5. Zero-Parameter Functions

Sometimes it's helpful to define functions that have zero parameters.
Note: you still need parentheses after the function name when defining and invoking the function.

Python has some useful built-in functions that take zero parameters, like random.

6. return vs. print

Try out the result of the following expressions:

IMPORTANT: If a function doesn't return a value (but only prints one as a side effect), don't use it in expressions where
a value is expected. Can you guess what result you'll get below:

DIGGING DEEPER: See the notes on the None value and the NoneType type to understand in more detail why this happens.

We can verify that None is not a string, by invoking the built-in function type:

7. Drills: Writing Functions

Define a function named four that always returns the string 'four'

Define a function named universeLifeAndEverything that always returns the number 42

Define a function named negate that returns the negation of its integer argument (e.g., -4 returns 4, 1 returns -1, 0 returns 0).

Define a function named hashtag which takes an argument (e.g., the string dogs) and returns it as a hashtag (e.g., the string #dogs)

Define a function named fruitfulSparkles that returns its argument surrounded by this string of sparkles before and after: ✧・゚: ✧・゚:. Note that we've stored these sparkles in the variable SPARKLES to reduce your copy-pasting work.

Define a function named longer that returns the length of the longer of two strings provided as its arguments

Define a function named squarea that takes the integer side-length of a square and returns the square's area

Define a function named petCount that takes three parameters, dogs, cats, and fish and returns the total number of animals (the sum of the 3 arguments)

Define a function named circleArea that takes the radius of a circle and returns the area of that circle. Remember that the area of a circle is equal to the radius squared times pi (math.pi).

8. Functions with side effect and no return value

A function doesn't always need to return a value. It might only display characters on the screen, or perform other side effects.

The following printTimeFromSeconds function use arithmetic operations and local variables to display the time for a given number of seconds.

9. Exercise 2: Incremental Development of Functions with Number Statistics

Incremental development is the process of slowly adding bits of code in a cumulative fashion and testing along the way to ensure proper functionality. We will illustrate incremental development using a function that prints out statistics about a number, similar to PS01.

Our function should take a single parameter called num and print out some simple statistics about the number. Below is an example output when our function is given the number three.

Your number is 3.
Your number squared is 9.
Your number has a remainder of 1 when divided by 2.

In the box below, focus on the header definition and simply have the function print out three and nothing else. It's always important to start simple.

Test to make sure your function properly works by calling it in the box below.

Adjust the body of the function so that it now prints out the first line of text.

Test to make sure your function properly prints the first line by calling it in the box below.

Add to the body of your function by printing out second line of text.

Test to make sure your function properly prints the first two lines by calling it in the box below.

Complete the function by adding to the body of your function so that it prints the final line.

Test to make sure your function properly works.

Incremental development is a key tool for writing code, especially complex code! We will employ this strategy as the semester progresses and we learn more cool coding concepts.

10. Exercise 3: Old Macdonald's Song

Write a function named verse to generate verses of the song, Old MacDonald had a farm.
What should the function parameters be?

Old MacDonald had a farm, EE-I-EE-I-O,
And on that farm he had a cow, EE-I-EE-I-O,
With a moo moo here and a moo moo there
Here a moo, there a moo, everyone a moo moo
Old MacDonald had a farm, EE-I-EE-I-O.

Old MacDonald had a farm, EE-I-EE-I-O,
And on that farm he had a chicken, EE-I-EE-I-O,
With a cluck cluck here and a cluck cluck there
Here a cluck, there a cluck, everyone a cluck cluck
Old MacDonald had a farm, EE-I-EE-I-O.

Old MacDonald had a farm, EE-I-EE-I-O,
And on that farm he had a horse, EE-I-EE-I-O,
With a neigh neigh here and a neigh neigh there
Here a neigh, there a neigh, everyone a neigh neigh
Old MacDonald had a farm, EE-I-EE-I-O.

Old MacDonald had a farm, EE-I-EE-I-O,
And on that farm he had a sheep, EE-I-EE-I-O,
With a baa baa here and a baa baa there
Here a baa, there a baa, everyone a baa baa
Old MacDonald had a farm, EE-I-EE-I-O.

Test your function below to generate a few different verses.

11. Functions with Graphics

We can also use functions to help us easily implement turtle graphics. But first let's motivate the need for functions. Here is a turtle picture below that makes three stars. Remember to first import the necessary turtle modules.

While the above code works perfectly well, it's rather long and repetitive. How can we use functions to abstract away the similar elements between these three stars but still capture their differences? First think about what is similar:

Now consider what is different:

Key idea: The body of a function should capture the similarities amongst code and the parameters should express the differences.

To test out our brand new function, first clear and reset the turtle screen

Now let's make three function calls using our new function. Note that these functions do not need to return a value because we are simply drawing the graphics.

Our star example is a great instance of the power of abstraction. Remember that abstraction is the process of hiding inner details and capturing essential similarities. Here the implementation of our function captures what is similar among all five-pointed stars and wraps those details in a function. The contract of the function allows the users to pass arguments to express the differences among stars.

You may notice some repetition within the function star, in particular the repeated calls to fd(length) and rt(144). We can reduce this repetition through iteration. We will get there in a few weeks!

12. Exercise 4: Colorful Stars

Suppose we want to be able to change the pen color for each star so the outline is a different color. How should we amend our function to capture this difference? You can change the pencolor with the function pencolor(color) where color is the color of the pen as a string. Write your answer below.

13. Exercise 5: drawRectangle

You have been using the python module turtleBeads.py. It was developed by our lab instructor Peter Mawhorter. Let's try and implement some of the functions provided to you by turtleBeads.py.

Right now turtleBeads.py has a function called drawRectangle which draws a centered rectangle about the location of the turtle of height height and width width.

Below write your own implementation of drawRectangle. Note you will want to use penup and pendown since the rectangle needs to be centered about the starting position of the turle.

Test your code below.

14. Exercise 6: drawSquare

turtleBeads.py also provides a very similar function to drawRectangle(width, height) called drawSquare(size). drawSquare is self-explanatory. It is a function that draws a square centered around the current location of the turtle. Below implement drawSquare. Be judicious though. How is a square similar to a rectangle? Can you use something you've already created to implement drawSquare?

Test your code below.

15. Fish Tank

Below is some code to draw a fish with a yellow body, black eye, and a green tail.

Our function is rather limited in that it always draws the same fish in the exact same position and orientation. How can we expand our fish function to make it more flexible for drawing different kinds of fish? First, let's identify some characteristics that should be different among fish?

What should be similar for all fish? Well it should be made of an ellipse, circle, and triangle and all of those pieces should still be proportional to each other. Below, amend the function header for fish below to capture these five differences and then implement each of the differences we stated above. Work incrementally! I suggest going in the order stated in our list above.

Below test your code. You should have a very pretty fish tank with different fish.

One important point to note. A key aspect that made amending the staticFish function much less laborious was that the function didn't rely on teleport() to move the turtle from shape to shape. Why was that helpful? Changing the angle of the entire fish becomes much more complex if you need to recalculate the x and y coordinates of each teleport to account for the angle.

16. Fruitful Graphics

We say that a function is fruitful if it returns a value. If a function does not return a value, then we say the function is not fruitful. Technically, functions without return do in fact return None but None serves as a placeholder to represent nothing. All of the above graphic functions we have worked with have not been fruitful. They draw pictures, which are side-effects, but do not return anything. Let's now make some fruitful turtle graphics that return key statistics about the pictures drawn.

Here is a simple example below that draws a triangle.

Suppose we wanted to draw a triangle but also return the perimeter. We can add to the function above by simply returning the perimeter at the end.

17. Exercise 7: Fruitful Square

Below write a function that draws a square of side size and returns the perimeter of the square. Unlike the drawSquare function from turtleBeads.py, let's not center the square around the starting point for simplicity. Instead the starting point should be the upper left corner of the square.

Test your code below. It should return 400.

Now that we have two functions that can return perimeter, it becomes easy to get the perimeter of a canvas of shapes.

18. Practice Writing Functions

Pick one of the following and write a new function. It's good to have practice translating the English description into Python.

Pick one of the following and write a new function. It's good to have practice translating the English description into Python.

A. squareDiff

Write a function called squareDiff that takes two numbers and returns the positive difference between their squares (you can use abs()). squareDiff(4, 3) returns 7; squareDiff(5, 11) returns 96. thon.

B. lottery

Given a function lucky() that returns a random integer between 1 and 100, write a function called lottery that will print 3 random lottery numbers with each number separated by a space.

For example, lottery() might print 57 81 41.

C. greeting

Write a function called greeting that asks for a user’s name using input(), and then prints a personalized greeting. E.g. Please tell me your name: Joyce
“Hi Joyce, hope you’re having a great day!” or something similar.

D. splitSquare

Write a function called splitSquare that takes 2 colors and draws a size square using turtleBeads, where the left half is filled with one color, and the right half with the other color. For example, here is the picture drawn when we call splitSquare(100, 'black', 'orange'):