Page 131 -
P. 131
set parameters
Use parameters to avoid duplicating
functions
Just like it’s a bad idea to use copy’n’paste for repeated usages of code, it’s
also a bad idea to create multiple copies of a function with only minor
differences between them. Look again at the proposed send_to_
twitter_price_low() and send_to_twitter_emergency()
functions on the previous page; the only difference between them is the
message they send.
A parameter is a value that you send into your function. Think of it as
the opposite of what you get when you return a value from a function:
Call the function
and send 5.51 as a
parameter.
... send_to_
send_to_twitter('5.51') twitter() Connect to Twitter and
... send the message with the
price to the CEO.
Return control to the
calling code.
The parameter’s value works just like a variable within the function, except In this version of the function,
for the fact that its initial value is set outside the function code: the “msg" variable is set to
the value passed in by the call
to “send_to_twitter(‘5.51’)".
def send_to_twitter(msg):
password_manager = urllib.request.HTTPPasswordMgr()
...
password_manager.add_password("Twitter API",
send_to_twitter('5.51')
"http://twitter.com/st
...
http_handler = urllib.request.HTTPBasicAuthHandler(pas
page_opener = urllib.request.build_opener(http_handle
urllib.request.install_opener(page_opener)
96 Chapter 3
params = urllib.parse.urlencode( {'status': msg} )
resp = urllib.request.urlopen("http://twitter.com/sta
resp.read()

