Week 5: Returns, Arguments, Logic

Reading: Think Python Chapter 6

Notes

Review - Function return

We have seen built-in functions that return a value after evaluation, such as float:

x = float(3)
print(x)
3.0

We have also seen how print does not return anything (None):

y = print("this gets printed")
this gets printed
print(y)
None

We have also written our own functions, so far without returning anything:

def print_cube(in_value):
    print(in_value * in_value * in_value)

Calling the function results in the print statement running (and printed output). However, nothing is returned.

Defining return Values

We can write functions so that they do return something. This is one of the most powerful concepts in computer programming.

To make your function return a value, use the keyword return at the end of the function:

function_return.py
def return_double(x):
    y = 2 * x
    return y

d = return_double(3)
print(d)

When execution inside a function reaches a return statement:

  • Execution inside that function ends
  • The return value is brought back to the function call
    • The value “replaces” the function call
    • This is similar to evaluation of an expression

Note that nothing is printed by the function itself!

  • The function call on line 5 results in a value being returned and assigned to d
  • There is only printed output from the explicit call to print on line 6

A function can have multiple return statements, but remember that the function ends the first time any return statement is reached.

An example. This function returns True if the input is an integer with multiple digits, otherwise it returns False.

multiple_return.py
def multiple_digits(x):
    if type(x) != int:
        return False
    elif x >= 10:
        return True
    elif x <= -10:
        return True
    else:
        return False

i = multiple_digits(5)
j = multiple_digits('lemon')
k = multiple_digits(-12)

Note that this program has no printed output, because there are no calls to print.

Multiple Arguments

A function can have any number of arguments. We’ve defined functions with no arguments and one argument. Multiple arguments are similar:

multiple_args.py
def smaller(a, b):
    if a < b:
        return a
    elif b < a:
        return b
    else:
        return a

x = smaller(3, 4)
print(x)

Arguments are passed into the function in the same position as the function call. Since 3 is the first argument, it becomes a when the function is called; likewise 4 becomes b.

Remember: if you define a function as needing a certain number of arguments, it must be called with that number of arguments. Otherwise, you’ll get an error.

Combining Conditionals

Conditional expressions can be combined and modified with three additional logic operators: and, or, and not.

  • The and operator will evaluate to True if both sides of the and are True.
A B A and B
True True True
True False False
False True False
False False False
  • The or operator will evaluate to True if either (or both) sides of the or are True.
A B A or B
True True True
True False True
False True True
False False False
  • The not operator reverses any boolean coming after it.

We can look at examples of these expressions using the interpreter:

(4 < 5) and (2 < 0)
False
x = 2
(x == 2) or (x == 3)
True
not (3 < 4)
False

These evaluate to bools - which means they can be used with conditionals!

logic_conditions.py
x = 2
if (x == 2) or (x == 3):
    print("x is either 2 or 3")

Practice

Practice Problem 5.1

Practice Problem 5.1

Rewrite the multiple_digits function from the notes, using a different sequence of if, elif and else statements (with different conditions).

Practice Problem 5.2

Practice Problem 5.2

Rewrite the smaller function from the notes. Keep the existing functionality, but add a check to see if the input arguments are numbers (ints or floats). If either argument isn’t a number, return False.

Practice Problem 5.3

Practice Problem 5.3

Write a function even_smaller that takes three integer arguments and returns the smallest of the three. You can assume that the arguments are all integers.

Practice Problem 5.4

Practice Problem 5.4

Write a function n_times that takes two arguments. The first is an integer, the second is a string. If the integer is greater than 0, return the string “multiplied” by the integer:

  • n_times(1, "ok") returns string "ok"
  • n_times(3, "times") returns string "timestimestimes"

If the integer is less than 1, return an empty string "".

Recall: using the * operator between a string and an integer will repeat the string in the manner desired. Try it out in the interpreter.

Practice Problem 5.5

Practice Problem 5.5

Write a function i_before_j that takes two arguments, both strings. Return a string in the format shown below, with the correct alphabetical order between the two strings:

  • i_before_j('dog', 'cat') returns string 'cat before dog'
  • i_before_j('coffee', 'supper') returns string 'coffee before supper'
  • i_before_j('practice', 'success') returns string practice before success'

Remember that > and < between strings is based on alphabetical order.

Homework

  • Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.

  • Double check your file names, printed output, and return values. These need to be exact matches for you to get credit.

  • Going forward, you will need to write functions that return instead of print. Confusing these two is a common error - take care to avoid it!

Homework Problem 5.1

Homework Problem 5.1 (25 pts)

Write a function ordered_triple that takes three arguments, all numbers.

Return a string consisting of the three numbers in numerical order, smallest to largest, separated by spaces, with no trailing space:

  • ordered_triple(5, 2, 3) returns string “2 3 5”
  • ordered_triple(1, 0, 1) returns string “0 1 1”
  • ordered_triple(1, -2, -3) returns string “-3 -2 1”

Submit as ordered_triple.py.

Homework Problem 5.2

Homework Problem 5.2 (25 pts)

Write a function smallest_positive that takes two arguments, both numbers, and returns the smallest positive number of the two (at least one of them will be positive).

  • smallest_positive(1, 2) returns integer 1
  • smallest_positive(-1, 2) returns integer 2

Submit as smallest_positive.py.

Homework Problem 5.3

Homework Problem 5.3 (25 pts)

Write a function three_or_four. It will take one argument, which will be one of these:

Threes:

  • int 3
  • float 3.0
  • str '3'
  • str 'three'

Fours:

  • int 4
  • float 4.0
  • str '4'
  • str 'four'

Return either int 3 or int 4, corresponding to the input value.

  • three_or_four('four') returns int 4
  • three_or_four(3) returns int 3

Submit as three_or_four.py

Homework Problem 5.4

Homework Problem 5.4 (25 pts)

Write a function three_digits that takes a single integer argument and returns True if the integer has exactly three digits and False otherwise.

  • three_digits(-123) returns True
  • three_digits(1001) returns False
  • three_digits(101) returns True
  • three_digits(-20) returns False
  • three_digits(-300) returns True

Submit as three_digits.py.