When you leave a function its variables get thrown away

Each time you call a function, Python creates a new stack frame to record new variables. But what happens when the function ends?

The computer throws away the function's stack frame!

Be this undev 4 ior

Be this undev 4 ior

Remember: the stack frame is there to record local variables that belong to the function. They are not designed to be used elsewhere in the program, because they are local to the function. The whole reason for using a stack of variables is to allow a function to create local variables that are invisible to the rest of the program.

And that's what's happened with the password variable. The first time Python saw it was when it was created in the set password () function. That meant the password variable was created on the set password() function's stack frame. When the function ended, the stack frame was thrown away and Python completely forgot about the password variable. When your code then tries later to use the password variable to access Twitter, you're outta luck, because it can't be found anymore...

When a variable's value CANNOT be seen by some code, it is said to be "out of scope."

This is the start of the program. Write a modified version of this code that will allow the send_to_twitter () function to see the password variable.

Hint: you might not need to use a function.

import urllib.request import time

You need to rewrite this secW.

def set_password():

password="C8H10N4O2

set password()

def send_to_twitter(msg):

password_manager = urllib.request.HTTPPasswordMgr() password_manager.add_password("Twitter API",

"http://twitter.com/statuses", "starbuzzceo", password) http_handler = urllib.request.HTTPBasicAuthHandler(password_manager) page_opener = urllib.request.build_opener(http_handler) urllib.request.install_opener(page_opener) params = urllib.parse.urlencode( {'status': msg} )

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params) resp.read()

Write youV new vevsion heve-

create the password variable

This is the start of the program. You were to write a modified version of this code that will allow the send_to_twitter () function to see the password variable.

Hint: you might not need to use a function.

import urllib.request import time def set_password():

password="C8H10N4O2"

set password()

You needed to rewrite this section.

def send_to_twitter(msg):

password_manager = urllib.request.HTTPPasswordMgr() password_manager.add_password("Twitter API",

"http://twitter.com/statuses", "starbuzzceo", password) http_handler = urllib.request.HTTPBasicAuthHandler(password_manager) page_opener = urllib.request.build_opener(http_handler) urllib.request.install_opener(page_opener) params = urllib.parse.urlencode( {'status': msg} )

resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params) resp.read()

Was this article helpful?

0 0

Post a comment