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’!
len(<some_list>)
is a functionSo 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 functionBecause print(...)
encapsulates the process of sending output to the command line, a file, or even a database or API!
All function ‘calls’ looking something like this:
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:
By ‘simple’ I don’t mean easy, I mean it does one thing only:
We then run it with:
And that produces:
We can pass information to a function if we tell the function what to expect:
Now we can do this:
And that produces:
We can also get information out of them!
Now we can do this:
output = hello("new programmers")
print(output.title())
# Same as: print(hello("new programmers").title())
And this produces:
This can also be written:
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.
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
Functions • Jon Reades