object scope

J

J. Peng

Please see the code below,what's the scope for object "name"?
I thought it should be located in the while block, but it seems not
really,it can be accessed out of while (the db[name] statement).Thanks
in advance.


db = {}
def newuser():
prompt = 'login desired: '
while 1:
name = raw_input(prompt)
if db.has_key(name):
prompt = 'name taken, try another: '
continue
else:
break
pwd = raw_input('passwd: ')
db[name] = pwd
 
D

Dennis Lee Bieber

Please see the code below,what's the scope for object "name"?

Please repost using a client that doesn't left justify all lines --
your post has lost all indentation, so it is nearly impossible to
determine what constitutes the while block.
I thought it should be located in the while block, but it seems not
really,it can be accessed out of while (the db[name] statement).Thanks
in advance.
Guessing at the indentation:
db = {}
def newuser():
prompt = 'login desired: '
while 1:
Any recent Python should take

while True:
name = raw_input(prompt)
if db.has_key(name):
prompt = 'name taken, try another: '
continue

continue is not needed
else:
break

The whole loop can turn into

while True:
name = raw_input(prompt)
if name not in db: break
prompt = "'%s' is in use, choose another: " % name

pwd = raw_input('passwd: ')
db[name] = pwd

The scope of "name" is the entire function; lacking a "global name"
statement, AND being on the left side of an assignment, it is a function
local name.
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
J

J. Peng

Dennis Lee Bieber 写é“:
The scope of "name" is the entire function; lacking a "global name"
statement, AND being on the left side of an assignment, it is a function
local name.

Thank you. Does python have so-called 'block scope' object?
or if you can,please show me the doc for python's object scope.
 
G

George Sakkis

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top