return statement

Inside a function the return causes immediate termination of the function's execution, and returns to point of invocation.

A return is implicitly executed at the end of each function, if an explicit return is not used.

In the example below the getWishes() function returns explicitly a string value, whereas the happyNewYear() function returns None implicitly.

Return values

A returned value, from a function should:

Conditional return

Often the return value from a function depends on some conditional logic, e.g. an if statement.

In those cases make sure that every possible path has a return.

Incremental Development

As you develop more complicated functions and programs, it will be very beneficial to you if you take an incrementatl approach to your problem solving workflow.

Start small, i.e. focus on one small aspect of the solution, verify each step with print statements and once happy with result, refactor if you can.

Try to follow these steps basically:

  1. Start with a working program and make small incremental changes to it. That way you will know when an errors creeps in.

  2. To aid in debugging, use local variables, which you can then print and check.

  3. See whether or not refactoring makes sense; keep readability in mind.

Let's look at an example of computing the distance between two points:

$d = \sqrt{(x2-x1)^2 + (y2-y1)^2}$

Our process:

1. Start with a simple working function; deal with details later

2. Use local vars for check points

3. Refactor

Composition

You can define a function that calls upon other functions to do the actual work. This technique is called composition and reduces/eliminates redundancy and its associated potential errors.

Assume you want to compute the area of a circle given two points; the center of the circle and a point on its perimeter.

circle center perimeter

Boolean Functions

The relational operators (<, <=, >, >=) and equality operators (==, !=) return a Boolean (True or False) result.

It is more readable if you assign such results to a boolean type variable.

Boolean functions can be used to hide complicated boolean expressions, thus making your code easier to write and understand.

Boolean functions should start with is to indicate their True / False nature.

Some Recursive Problems

Recursion is a great technique for solving problems. The solution is actually expressed in terms of the problem itself, a cyclical answer of sorts.

Factorial

We'll start with the solution to the factorial of $n$, expressed as $n!$.

By definition we have:

$0! = 1$

$n! = n(n-1)!$

Fibonacci Series

The fibonacci series is defined as follows:

$fibonacci(0) = 0$

$fibonacci(1) = 1$

$fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)$ for $n >= 2$

Sidenote

Notice how much redundant computations are performed in just trying to determine fibonacci(5).

We can improve the solution by:

a) using iteration rather than recursion and

b) storing each evaluated result, when first encounted, in a dictionary (see later on). Each subsequent occurence will then be retieved rather than recomputed.

Practice problems

Create a separate Python source file (.py) in VSC to complete each exercise.


p1: mathOperations.py

Define four functions to carry out each of the four mathematical operations, add, substract, multiply, and divide. Each function should accept two parameters and return the corresponding result.

Call each function and print the results as:

2 + 4 = 6
2 - 4 = -2
2 * 4 = 8
2 / 4 = 0.5

p2: palindrome.py

A palindrome is a word that is spelled the same backward and forward, like "noon" and "redivider". Recursively, a word is a palindrome if the first and last letters are the same and the remaining middle is a palindrome.

The following are functions that take a string argument and return the first, last, and middle letters:

def first(word):
  return word[0]

def last(word):
  return word[-1]

def middle(word):
  return word[1:-1]

We shall study these techniques later on in the course.

  1. Type these functions into a script and test them out. What happens if you call middle() with a string with two letters? One letter? What about the empty string, which is written as '' and contains no letters?

  2. Write a recursive function called is_palindrome() that takes a string argument and returns True if it is a palindrome and False otherwise. Remember that you can use the built_in function len() to check the length of a string.


p3: power.py

A number, $a$ is a power of $b$ if it is divisible by $b$ and $a/b$ is a power of $b$. Write a recursive function called is_power() that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case.


p4: gcd.py

The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.

One way to find the GCD of two numbers is base on the observation that if $r$ is the remainder when $a$ is divisible by $b$, then $gcd(a, b) = gcd(b, r)$. As a base case, we can use $gcd(a, 0) = a$.

Write a recursive function called gcd() that takes parameters a and b and returns their greatest common divisor.

[Conditionals] [TOC] [Iteration]