Functions

Jon Reades

Let’s Get Lazy!

Functions ‘encapsulate’ a task (they combine many instructions into a single line of code). Most programming languages provide many built-in functions that would otherwise require many steps to accomplish, for example computing the square root of a number. In general, we don’t care how a function does what it does, only that it ‘does it’!

What Does a Function Look Like?

len(<some_list>) is a function

So len(...) encapsulates the process of figuring out how long something with ‘countable units’ actually is, whether it’s a string or a list.

print(<some_value>) is also a function

Because print(...) encapsulates the process of sending output to the command line, a file, or even a database or API!

So What Does a Function Look like?

All function ‘calls’ looking something like this:

function_name(...)

Where the ‘...’ are the inputs to the function; it could be one variable, 25 variables, a list, even another function!

And if the function ‘returns’ something it will look like this:

return_data = function_name(...)

As Code

data = [1,25,-4,14,7,9]
total = 0.0
count = len(data)
for i in data:
  total += i

print(total/count)

As Function

def calc_mean(numbers):
  total = 0.0
  count = len(numbers)
  for i in numbers:
    total += i
  return total/count

data = [1,25,-4,14,7,9]
print(calc_mean(data))

In Action!

def calc_mean(numbers):
  total = 0.0
  count = len(numbers)
  for i in numbers:
    total += i
  return total/count

data = [1,25,-4,14,7,9]
print(calc_mean(data)) # 8.666666666666666
data2 = [200000,2500000,-4,1400000,70,900000]
print(calc_mean(data2)) # 833344.3333333334

But Notice!

data    = [1,25,-4,14,7,9]
total   = 1
numbers = []

def calc_mean(numbers):
  total = 0.0
  count = len(numbers)
  for i in numbers:
    total += i
  return total/count

print(calc_mean(data))

# Why haven't these changed????
print(total)
print(numbers)

Simple Function

By ‘simple’ I don’t mean easy, I mean it does one thing only:

def hello():
  print("Hello world!")

We then run it with:

hello()

And that produces:

Hello world!

Passing in Information

We can pass information to a function if we tell the function what to expect:

def hello(name:str):
  print(f"Hello {name}!")

Now we can do this:

hello("new programmers")

And that produces:

Hello new programmers!

Getting Information Out

We can also get information out of them!

def hello(name:str) -> str:
  return f"Hello {name}!"

Now we can do this:

output = hello("new programmers")
print(output.title())
# Same as: print(hello("new programmers").title())

And this produces:

'Hello New Programmers!'

Writing a Function

def <function_name>(<var_name>: <var_type>) -> <var_type>:
  ...
  return <var>

This can also be written:

def <function_name>(<var_name>):
  ...
  return <var>

Python is ‘friendly’ in the sense that all of the <var_type> information is optional, but it will help you (and Python) to know what you were expecting to see happen.

Complicating Things…

ds2 = {
  'lat':[51.51,40.71,35.69],
  'lon':[0.13,74.01,139.68],
  'tz': [+0,-5,+8],
  'name':['London','New York','Tokyo']
}

def get_city_info(city:str, field:str, city_lookup:str='name', data:dict=ds2) -> str:
  return str(data[field][ data[city_lookup].index(city) ])

city = 'New York'
print(f"The latitude of {city} is {get_city_info(city,'lat')}")
# The latitude of New York is 40.71

Any time you type the same code more than twice… consider a function!

Resources