473,322 Members | 1,494 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

It's a bug!....but is it me or the script? (Global var assign)

Hey here's a relatively simple question...the code is for a mock-up passwd, usrname dict storagesystem. Why doesn't the variable enc behave globally (the admin function turns up a "local var referenced before assignment" error, when inputting 's')? In all likelyhood I've just managed to stare myself blind, so to anyone w/ a spare pair of eyes - the help would be appreciated. It's run under Python 2.3.0 in Win2k.

T/x
H

PS: I know it's long and I apologize, but basically it's just the first 8 lines that should matter.

-----------------------------------

#!/usr/bin/env python

import time
import rotor

passenc = rotor.newrotor('lockkey', 8)
db = {}
enc = 0

'Solution for exercise 7 a, b and c. Unresolved: Why is enc treated as global in newuser() but local in admin()?'

def newuser():
prompt = 'login desired: '
while 1:
name = raw_input(prompt)
if len(name) < 3:
prompt = 'name too short, try another: '
continue
elif db.has_key(name):
prompt = 'name taken, try another: '
continue
else:
break
pwd = raw_input('passwd: ')
# If admin has turned in encryption encrypt new pass. Unresolved issue regarding switching the feature on and off (conditional decrypt)
if enc:
pwd = passenc.encrypt(pwd)
time1 = time.time()
#creates the user w/ a name, pass and a timestamp for last login
db[name] = [pwd, time1, enc]
print name, db[name][0], db[name][1], db[name][2]

def olduser():
name = raw_input('login: ')
pwd = raw_input('passwd: ')
passwd = db.get(name)[0]
#Possible solution for conditional decrypt
if db.get(name)[2]:
passwd = passenc.decrypt(passwd)
#checks if pass is good and updates timestamp (saves a copy for comparison)
if passwd == pwd:
chktime = db[name][1]
time1 = time.time()
db[name][1] = time1
#checks if last login is less than four hours ago
if time1-chktime < 14400:
print 'You already logged in at '+time.strftime('%H:%M',time.localtime(chktime))
pass
else:
print 'login incorrect'
return

print 'welcome back', name

def admin():
prompt = """
(V)iew list of users
(D)elete user account
(S)et password encryption
(Q)uit

Enter choice: """

while 1:
adchoice = raw_input(prompt)
if adchoice not in 'vdqs':
prompt = 'invalid choice, try again: '
continue
elif adchoice == 'v':
for eachkey in db.keys():
print 'user', eachkey, 'has password', db[eachkey][0]
prompt = 'Enter new choice: '
continue
elif adchoice == 'd':
delusr = raw_input('User to remove: ')
if db.has_key(delusr):
del db[delusr]
prompt = 'User deleted. Enter new choice: '
else:
prompt = 'No such user. Enter new choice: '
continue
elif adchoice == 's':
if enc==1:
enc = 0
print 'Encryption off'
continue
else:
enc = 1
print 'Encryption on'
continue
elif adchoice == 'q':
break


def showmenu():
prompt = """
(N)ew User Login
(E)xisting User Login
(A)dministration
(Q)uit

Enter choice: """

done = 0
while not done:
chosen = 0
while not chosen:
try:
choice = raw_input(prompt)[0]
except (EOFError, KeyboardInterrupt):
choice = 'q'
print '\nYou picked: [%s]' % choice

if choice not in 'aneq':
print 'invalid menu option, try again'
else:
chosen = 1

if choice == 'q': done = 1
if choice == 'n': newuser()
if choice == 'e': olduser()
if choice == 'a': admin()

if __name__ == '__main__':
showmenu()

Jul 18 '05 #1
3 1876
Halfdan Holger Knudsen wrote:

Why doesn't the variable enc behave globally (the admin function turns
up a "local var referenced before assignment" error, when inputting 's')?


To use a variable globally, *if you're going to rebind it* (as in, assign to it)
you need to put a "global" statement at the top of each function which uses it.

If all you ever do is read the value, you don't need this, but you are trying
to rebind the name "enc" in some of those functions, so you must have a
"global enc" statement before you do that.

-Peter
Jul 18 '05 #2
JCM
You must declare a module-level variable global in a function if you
wish to assign to it:

x = 0

def f():
global x
x = 1
Jul 18 '05 #3
Halfdan Holger Knudsen wrote:
Hey here's a relatively simple question...the code is for a mock-up
passwd, usrname dict storagesystem. Why doesn't the variable enc behave
globally (the admin function turns up a "local var referenced before
assignment" error, when inputting 's')? In all likelyhood I've just
managed to stare myself blind, so to anyone w/ a spare pair of eyes - the
help would be appreciated. It's run under Python 2.3.0 in Win2k.

T/x
H

PS: I know it's long and I apologize, but basically it's just the first 8
lines that should matter.


When you try to make it shorter instead of staring yourself blind the chance
of finding the bug yourself increases rapidly:
e = 0
def fun(): .... if e == 0:
.... e = 1
.... fun() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in fun
UnboundLocalError: local variable 'e' referenced before assignment def fun(): .... global e
.... if e == 0:
.... e = 1
.... fun()
e 1


When you are rebinding a name (enc) anywhere inside a function it refers to
a local even before the actual rebinding is done, unless you explicitly
state you want it to refer to a global, i. e. say

global enc

Peter
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: vladserge | last post by:
Hi, can someone explain the behaviour of that snip public class Test { public static void main(String args) { try { Class c = Class.forName("BUG");
0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 259 open ( -5) / 2573 closed (+17) / 2832 total (+12) Bugs : 745 open ( +0) / 4405 closed (+21) / 5150 total (+21) RFE : 150 open...
4
by: Baoqiu Cui | last post by:
Today I was playing with a small Python program using Python 2.4 on Cygwin (up-to-date version, on Windows XP), but ran into a strange error on the following small program (named bug.py): ...
2
by: Leon Lambert | last post by:
I was wondering if someone could post some links to some bug pattern detector software for C#. I found this very interesting article about pattern detectors for Java so wanted to investiage one for...
6
by: Moshazu | last post by:
Take a look at the following code... dim newLabel as new Label with newLabel .autosize = true .text = "-00.00" .autosize = false end with
4
by: Marcus Kwok | last post by:
I found a bug in VC++ .NET 2003 regarding default initialization of arrays of primitives in a constructor initialization list, as detailed in this post:...
1
by: Eirik Eldorsen | last post by:
I've found a bug on the menu control when using Firefox. Where should i report the bug? The bug appears if you click on an level-1 item (horisontal menu), and moves the mousecursor to the popup...
158
by: Giovanni Bajo | last post by:
Hello, I just read this mail by Brett Cannon: http://mail.python.org/pipermail/python-dev/2006-October/069139.html where the "PSF infrastracture committee", after weeks of evaluation, recommends...
0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 385 open (+21) / 3790 closed (+21) / 4175 total (+42) Bugs : 1029 open (+43) / 6744 closed (+43) / 7773 total (+86) RFE : 262 open...
0
by: LiveTecs | last post by:
http://www.livetecs.com TimeLive Web Collaboration Suite is an integrated suite that allows you to manage project life cycle including tasks, issues, bugs, timesheet, expense, attendance. ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.