python - Variable referenced before assignment error -


i trying make code ask password , receive it, if password correct happen if not else happen, when tried code gives me error on line 10, , 18:

if (password == 'xxxx'): unboundlocalerror: local variable 'password' referenced before assignment 

here code:

import random  def askforpassword():     print('welcome machine!')     print('enter password: ')     password = input()  def getpassword():     while passwordtry != 0:        if (password == 'xxxx'):         print('correct')        else:         passwordtry -= 1         print('incorrect!')  passwordtry = 5 askforpassword() getpassword() 

since you're asking why doesn't work, let's @ error get:

traceback (most recent call last):   file "pw.py", line 18, in <module>     getpassword()   file "pw.py", line 10, in getpassword     if (password == 'xxxx'): unboundlocalerror: local variable 'password' referenced before assignment 

what it's saying trying access local variable 'password', , haven't created such local variable.

if want use global variable, explicitly:

def getpassword():     global password     while passwordtry != 0:        if (password == 'xxxx'):         print('correct')        else:         passwordtry -= 1         print('incorrect!') 

but still won't work, because nobody's setting global variable, either. need change askforpassword too:

def askforpassword():     global password     print('welcome machine!')     print('enter password: ')     password = input() 

this still has lot of problems. example, call askforpassword once, not once each time through loop, it's going ask once , print incorrect! 5 times. also, better not use global variables—has askforpassword return password, , store in local variable in getpassword.

def askforpassword():     print('welcome machine!')     print('enter password: ')     password = input()     return password  def getpassword():     while passwordtry != 0:        password = askforpassword()        if (password == 'xxxx'):         print('correct')        else:         passwordtry -= 1         print('incorrect!') 

and want return getpassword too, whoever calls knows whether succeeded or failed.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -