1 of 36

Creating Your Own Functions

Creating functions and modules

Please download the lecture files...

1

2 of 36

Outline

  1. Review
  2. Creating your own functions
  3. Activity
  4. Terminology: parameters/arguments and return values
  5. Type hints and docstrings

2

3 of 36

Outline

  • Review
  • Creating your own functions
  • Activity
  • Terminology: parameters/arguments and return values
  • Type hints and docstrings

3

4 of 36

Using functions

What do you have to know to be able to use a function?

    • What the function does
    • Required arguments (and the valid data types)
    • Optional arguments (and valid data types)
    • What gets returned (if anything)

4

max()�???

1, 99, 123, 3

123

print()�???

‘Hello', ‘There’, end='!’

None

Outputs to screen

(side effects)

5 of 36

Using functions

  • Do you need to know how a function works in order to use it?
    • No! Think of it as a black box
  • What do you do if you don’t know how to use a function?
    • Use the built-in help() function
    • Google it
    • Trial and error; just experiment!

5

6 of 36

Activity 1: Using only built-functions, write some programs...

Using the operator functions from the operator module, write a program to calculate the hypotenuse of a right triangle where side a=5 and side b=12.

On your own, try to complete the following:

  1. lectures/lecture06/01_operator_functions.py
  2. lectures/lecture06/02_operator_functions.py

Don’t look at the answers yet!

6

7 of 36

What if you needed to do it for 1,000 triangles?

  • Would I need to manually do that 1,000 times?
  • How could I simplify things (and therefore save myself time and make it less likely to make mistakes)?

7

8 of 36

Outline

  • Review
  • Creating your own functions
  • Activity
  • Terminology: parameters/arguments and return values
  • Type hints and docstrings

8

9 of 36

Recall: The Big Ideas with Functions...

  1. Functions are a way of encapsulating, organizing, and reusing code
  2. They help us “abstract” away complexity and allow you to reason about your code at a higher level:
    1. You may not want to know how the hypotenuse is calculated, so long as it always give you the correct answer (given the inputs)
  3. They allow you to perform the same operations on different data values — also called arguments

9

10 of 36

So how do I make my own?

10

11 of 36

Functions: header and body

def name_of_function(parameters):

statement 1

statement 2

...

return some_value

11

HEADER�Specifies the name of the function and the data that it needs. Also called the SIGNATURE

BODY�One or more indented statements that the function will execute when called

12 of 36

def name_of_function(parameters):

statement(s)

return some_value

12

Keyword def marks the start of function header

A function name to uniquely identify it (snake case)

parameters (the way we pass data to a function)

colon (:) marks end of function header

function body has 1 or more statements, which have same indentation level (usually 4 spaces)

An optional return statement to return a value from the function

13 of 36

Functions must be invoked in order to execute

name_of_function(arguments)

13

arguments (specific data values that are passed into a function)

  • Arguments must conform to the function header �rules (or specifications)
  • Pay attention to data type: functions are always designed to manipulate particular data types

14 of 36

Let’s take a look at some examples...

14

15 of 36

Function with no parameters, no return value

# define the function

def say_hello():

print('Hello there!')

print('How are you this morning?')

# call(invoke) the function

say_hello()

say_hello()

15

lectures/lecture06/03_function_no_parameters_no_return.py�Visualize: https://goo.gl/eqxY3b

16 of 36

Function with a required parameter, no return value

# define the function

def say_hello(name: str):

print('Hello there,', name, end='!')

print('How are you this morning?')

# call(invoke) the function

say_hello('Varun')

say_hello('Grace')

16

arguments

Parameter of type string

lectures/lecture06/04_function_parameters_no_return.py | Visualize

17 of 36

Function with a no parameters, returns a value

# define the function

def get_todays_date():

from datetime import datetime

return datetime.now().date()

# call(invoke) the function

todays_date = get_todays_date()

print('Today\'s date is', todays_date)

17

return statement

assigning return value to variable

lectures/lecture06/05_function_no_parameters_return.py | Visualize

18 of 36

Function with parameters, returns a value

# define the function

def add_em(num_1: float, num_2: float):

return num_1 + num_2

# call(invoke) the function

result = add_em(33, 44)

print('The sum is:', result)

result = add_em(3, 55)

print('The sum is:', result)

18

return statement

assigning return value to variable

lectures/lecture06/06_function_parameters_return.py | Visualize

Parameters of type float

19 of 36

Outline

  • Review
  • Creating your own functions
  • Activity
  • Terminology: parameters/arguments and return values
  • Type hints and docstrings

19

20 of 36

Activity 2: Make your first function...

20

lectures/lecture06/07_activity.py

21 of 36

Activity 2: Make your first custom function

Inside of the lectures/lecture06/07_activity.py file, create three custom functions:

  1. get_area to calculate the area of right triangle
  2. get_perimeter to calculate the perimeter of a right triangle
  3. get_hypotenuse that calculates the hypotenuse of any triangle.

When you’re done, invoke that function using the following triangle dimensions:

side_a = 5, side_b = 12

side_a = 3, side_b = 5

side_a = 4, side_b = 4

If you get done early, try lectures/lecture06/08_activity.py

21

22 of 36

Outline

  • Review
  • Creating your own functions
  • Activity
  • Terminology: parameters/arguments and return values
  • Type hints and docstrings

22

23 of 36

What is the difference between a parameter and an argument?

23

24 of 36

Parameters & Arguments

parameter :: variable in function definitionA name, used inside a function, to refer to the data value (argument) passed into it. Parameters are variables.

argument :: data specified when function invokedA value provided to a function when the function is called/invoked. This value is assigned to the corresponding parameter in the function. The argument can be the result of an expression which may involve operators, operands and calls to other functions.

24

25 of 36

2 Types of Parameters

Positional parameters

  • Positional parameters are required (although there is one special case to be discussed later in the course)
  • The order in which they are passed matters

Keyword parameters

  • Keyword parameters are always optional
  • They are always passed into a function after the positional parameters, but the order of keyword parameters doesn’t matter.
  • Keyword parameters always have a default value

25

26 of 36

Function with 1 positional parameter

# defining the function

def say_hello(name: str):

print('Hello there,' + name + '!')

print('How are you this morning?')

# calling (invoking) the function

say_hello('Varun')

say_hello('Grace')

26

Arguments

Parameter (positional)

27 of 36

Function with 2 positional parameters

# defining the function

def say_hello(name: str, time_of_day: str):

print('Hello there,' + name + '!')

print('How are you this ' + time_of_day + '?')

# calling (invoking) the function

say_hello('Varun', 'morning')

say_hello('Grace', 'evening')

27

2 positional parameters

Arguments

28 of 36

Function with 1 keyword parameter

# defining the function

def say_hello(time_of_day: str='morning'):

print('How are you this ' + time_of_day + '?')

# calling (invoking) the function

say_hello()

say_hello(time_of_day='evening')

28

keyword parameter

No keyword argument (uses default)

Keyword argument overrides default

29 of 36

Function with positional and keyword parameters

# defining the function

def say_hello(name: str, time_of_day: str='morning'):

print('Hello there,' + name + '!')

print('How are you this ' + time_of_day + '?')

# calling (invoking) the function

say_hello('Varun')

say_hello('Grace', time_of_day='evening')

29

positional & keyword parameters

No keyword argument (uses default)

Keyword argument overrides default

30 of 36

Fruitful and non-fruitful functions

Fruitful

A function that returns a value

def get_area_of_rect(side1: float, side2: float):� return side1 * side2

�Non-fruitful

Does something but does not return a value

def say_hello(name):� print('Hello there,' + name + '!')

30

31 of 36

Fruitful functions (have return values)

# defining the function

def get_hypotenuse(side_a: float, side_b: float):

sum_of_squares = side_a** 2 + side_b ** 2

return sum_of_squares ** 0.5

# calling (invoking) the function

hypotenuse1 = get_hypotenuse(55, 25)

hypotenuse2 = get_hypotenuse(515, 467)

print(hypotenuse1)

31

return value

return value stored in variable

32 of 36

Quiz

What’s an example of a function we used in HW1 that does not return a value?

  • print()
  • help()

What’s an example of a function we used in HW1 that does return a value?

  • input()
  • int()
  • float()
  • eval()

32

33 of 36

Outline

  • Review
  • Creating your own functions
  • Activity
  • Terminology: parameters/arguments and return values
  • Type hints and docstrings

33

34 of 36

Things that your interpreter doesn’t care about (but that you should): Type Hints

  • Type Hints: Python doesn’t care whether or not your function signature has a data_type, but it’s *very useful for code readability:

def say_hello(name, time_of_day='morning'):

...

def say_hello(name: str, time_of_day: str='morning'):

...�

34

35 of 36

Things that your interpreter doesn’t care about (but that you should): Docstrings

  • Docstrings: a way of documenting your code. Useful for helping others who might use your function later on; and also about helping your future self out when you revisit this code...wait...what did this do again?

35

36 of 36

Things that your interpreter doesn’t care about (but that you should): Docstrings

def add_em(num_1: float, num_2: float):

'''

Adds two numbers together.

Args:

num_1(float): the first number in the addition operation.

num_2(float): the second number in the addition operation.

Returns:

float: the sum of the two numbers

'''

return num_1 + num_2

36