Python error: global name Xis not defined - python

I've attached my Python Code below for a program our teacher as gave us in school. I keep on encountering an error "global name 'passwordValid' is not defined" and cannot find any way to solve this. This error occurs in the Password.append(passwordValid) line.
global firstName
global lastName
global cateGory
global passwordValid
global passwordNew
firstName = ""
lastName = ""
cateGory = ""
def newMember():
#Recieve user input to assign values to variables
firstName = str(input("Please enter your first name."))
lastName = str(input("Please enter your last name."))
#Validation to reject unspecifyed category input
cateGoryValid = False
while cateGoryValid == False:
cateGory = str(input("PLease enter your category from the following: (Junior,Adult,Senior)"))
cateGory = cateGory.lower()
cateGory = cateGory.capitalize()
if cateGory == "Junior" or cateGory == "Adult" or cateGory == "Senior":
cateGoryValid = True
else:
cateGory = str(input("PLease enter your category from the following: (Junior,Adult,Senior)"))
def passwordValidation():
#initalising global variables
#Creating Variables
Valid = False
firstCharacter =""
firstValue = 0
lastCharacter =""
lastValue = 0
passwordNew = ""
passwordValid = []
#Create conditional loop to validate the password
while Valid == False:
passwordNew = str(input("Please enter a new password"))
#Assigns both the first and last values of the password as variables
firstCharacter = passwordNew[0]
lastCharacter = passwordNew[-1]
#Assigns both values as ASCII characters
firstValue = ord(firstCharacter)
lastValue = ord(lastCharacter)
#Ensures password is within boundaries using ASCII characters
if firstValue >= 65 and firstValue and lastValue >= 35 and lastValue <=37:
passwordValid = passwordNew
Valid = True
return passwordValid
def valuesAppend():
return passwordValid
global Forname
global Surname
global Category
global Password
Forename = [""]
Surname = [""]
Category =[""]
Password = [""]
Position = 0
Members = ["","","",""] * 11
#Reading the text file
file = open("members.txt","rt")
#Create loop to assign all fields to a record
for line in file:
fields = line.split(",")
Members[Position] = [fields[0],fields[1],fields[2],fields[3]]
#Appending the fields into a global variable
Forename.append(fields[0])
Surname.append(fields[1])
Category.append(fields[2])
Position = Position + 1
#Assigning new variables into the record
Forename.append(firstName)
Surname.append(lastName)
Category.append(cateGory)
Password.append(passwordValid)
file.close
def categoryInfo():
totalMembers = 0
totalMembers = len(Forename)
for counter in range(len(Forename)):
print(Forename[counter], Surname[counter],Category[counter])
print("There are:",Category.count("Junior"),"Junior members.")
print("There are:",Category.count("Adult"),"Adult members.")
print("There are:",Category.count("Senior"),"Senior members.")
print("The current total is:",totalMembers,"members.")
def main():
newMember()
passwordValidation
valuesAppend()
categoryInfo()
main()

There seems to be a few bits wrong with the way your code is structured.
Firstly, you don't need to define your variables as globals, you only need to use 'global variable' within the local scope of a function so it knows it's accessing a global variable e.g.
password = "Password"
print(password)
# prints "Password"
def update_pass():
global password # saying that the 'password' variable in this function refers to the global variable called 'password'
password = "New password"
update_pass()
print(password)
# prints "New password"
Secondly, this block of code doesn't fall under any function and therefore would try to run before your main() function. Ensure this is correctly indented
#Assigning new variables into the record
Forename.append(firstName)
Surname.append(lastName)
Category.append(cateGory)
Password.append(passwordValid)
Lastly, this function is quite strange
def valuesAppend():
return passwordValid
global Forname
# ...
Here, your valuesAppend() function will try to return passwordValid and that's it, once a return happens the rest of the code below isn't ran so you'll get no other use from your function
Hope this helps

Related

What am I missing in this python login function?

I am trying to write a login function using python. However, I can't seem to write the code for checking the username and password against the ones stored in a file. The specific error is NameError: name 'adusername' is not defined. How do I fix this?
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.write(adusername)
adfile.write(",")
adfile.write(adpassword)
adfile.write("\n")
adfile.close()
def adminverification():
adun = input("Enter your username:")
adpw = input("Enter your password:")
adinfo = open("adlogindetails.txt", "r")
for line in adinfo:
adun, adpw = line.split(",")
if adun == adusername and adpw == adpassword:
print("Login successful!")
adminoptions()
else:
print("Incorrect username/password")
roleselection()
adminverification()
You have not declared adusername and adpassword in adminverification(). So, it is causing the error. If you want to use the variables from adminlogindetails(), change the variables name since you have stored the details in adlogindetails.txt.
The below code should be changed as line variable contains the already stored username and password:
adun, adpw = line.split(",")
Change above piece of code to the shown below:
adusername, adpassword = line.split(",")
you can use this:
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.writelines(adusername + ',' + adpassword )
adfile.close()
def adminverification():
adun = input("Enter your username:").strip()
adpw = input("Enter your password:").strip()
with open("adlogindetails.txt", "r") as f:
lines = f.readlines()
i = 0
for line in lines:
adusername, adpassword= line.split(",")
adusername = str(adusername).strip()
adpassword = str(adpassword).strip()
if (adun == adusername) and (adpw == adpassword):
print("Login successful!()")
adminoptions()
break
else:
i += 1
if i >= len(lines): #If no any match upto last line, this will be true
print("Incorrect username/password")
roleselection()
break
adminverification()
First of all you are not calling adminlogindetails().
Also adusername is a local variable and you should either make it global using global adusername in the adminlogindetails function or declare it outside of the functions in the global scope.
See this - https://www.w3schools.com/python/python_scope.asp
This line is your problem:
adun, adpw = line.split(",")
"adun" and "adpw" are your inputs and you are overwriting them. Replace with this and it will be ok:
adusername, adpassword = line.replace("\n", "").split(",")
Note: "\n" needs to be removed for your comparison to be ok.

how can i fix: UnboundLocalError: local variable 'generate' referenced before assignment

Error: UnboundLocalError: local variable 'generate' referenced before assignment
why it's giving me this error?
Code
import string
import random
Password = ""
lettere = string.ascii_letters
numeri = string.digits
punteggiatura = string.punctuation
def getPasswordLenght():
lenght = input("How log do you want your password...\n>>> ")
return int(lenght)
def passwordGenerator(lenght):
caratteri = ""
requestPunteggiatutaIclusa = input("Punteggiatura (YES | NO)\n>>> ")
if requestPunteggiatutaIclusa.upper() == "YES" :
caratteri = f"{lettere}{numeri}{punteggiatura}"
generate(lenght)
elif requestPunteggiatutaIclusa.upper() == "NO" :
caratteri = f"{lettere}{numeri}"
generate(lenght)
else :
print("Error")
passwordGenerator(lenght)
return Password
def generate(lenght) :
caratteri = list(caratteri)
random.shuffle(caratteri)
Password = ""
for i in range(lenght):
Password = Password + caratteri[i]
i = i + 1
return Password
passwordGenerator(getPasswordLenght())
print(Password)
Result
How log do you want your password...
8
Punteggiatura (YES | NO)
yes
Traceback (most recent call last):
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 46, in <module>
passwordGenerator(getPasswordLenght())
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 33, in passwordGenerator
generate(lenght)
File "/Users/paolo/Desktop/COde/PY/passwordGenerator.py", line 19, in generate
caratteri = list(caratteri)
UnboundLocalError: local variable 'caratteri' referenced before assignment
Do you know what is local variable ?
caratteri = "" creates local variable which exists only inside passwordGenerator() but you try to use it in generate() when you use list(caratteri).
In generate() you create also local variable when you use caratteri = list(...) but you do this after trying to get value from caratteri - and this gives error local variable 'caratteri' referenced before assignment.
Better use variables explicitly - send them as arguments
generate(lenght, caratteri)
And the same problem you may have with Password.
You created global variable Password = "" but inside generate() you create local Password = "". In generate() you could use global Password to work with global Password instead of creating local Password but beetter use value which you return from function
Password = generate(lenghtt, caratteri)
My version with many other changes
import string
import random
# --- functions ---
def ask_questions():
length = input("Password length\n>>> ")
length = int(length)
# In Linux it is popular to use upper case text in `[ ]`
# to inform user that if he press only `ENTER`
# then system will use this value as default answer.
# I inform user that `N` is default answer.
# I don't like long answers like `yes`, `no` but short `y`, n`
# and many program in Linux also use short `y`,`n`
answer = input("Use punctuations [y/N]\n>>> ")
answer = answer.upper()
characters = string.ascii_letters + string.digits
if answer == "Y":
characters += string.punctuation
elif answer != "" and answer != "N":
print("Wrong answer. I will use default settings")
return length, characters
def generate(lenght, characters):
characters = list(characters)
random.shuffle(characters)
password = characters[0:lenght]
password = ''.join(password)
return password
# --- main ---
# I seperate questions and code which generates password
# and this way I could use `generate` with answers from file or stream
length, characters = ask_questions()
password = generate(length, characters)
print(password)
PEP 8 -- StyleGuide for Python Code

why i am getting blank list as output in python even after appending item in it?

#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.

UnboundLocalError: local variable 'username' referenced before assignment (in a return part of a function)

def login():
userinfo = open("userinfo.txt","r")
userinforec = userinfo.readline()
username1 = input("What is your username?\n")
while userinforec != "":
field = userinforec.split(",")
username = field[0]
password = field[1]
name = field[2]
age = field[3]
year = field[4]
mathseasy = field[5]
mathsmed = field[6]
mathshard = field[7]
hiseasy = field[8]
hismed = field[9]
hishard = field[10]
if username != username1:
print("Error, username not found")
break
else:
password1 = str(input("What is your password?\n"))
if password == password1:
print("password accepted")
writereport(username)
else:
print("Error, password not accepted")
login()
userinforec = userinfo.readline()
userinfo.close()
return username
Exactly as stated in the title, when I run this piece of code it says that in the final line (return username) is referenced before assignment.
UnboundLocalError: local variable 'username' referenced before assignment
I looked at other threads and it all occurred if the variable is outside of a function however here it is not. Do I still need to use global or is there another way to get around this?
If your while loop is never entered, e.g. because userinforec == "" you are returning username before assigning it with any value.
Add username = "" before your while loop so that is has a value, if it is never assigned during the while loop.

Manipulating Strings to return concatenated username

Whenever I try to display the Firstname with first initial attached to the end, I get an out of string index range error!
def ForeName():
return raw_input("Please enter your Forename: ")
def MiddleName():
return raw_input("please enter your middle name, if none leave blank: ")
def LastName():
return raw_input("Please enter your last name: ")
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT[0:] + LastNameT[0]
elif ForeNameT:
first_username = ForeNameT[0:][0] #i want to display the first name with the initial of the first name attached to the end of the first name.
else:
first_username = ForeNameT[0:] + MiddleNameT[0]
return first_username
print Test()
You can add an argument to Test function by doing def Test(name_method): and then set if to if name_method == 'without_middlename':.
Try to figure out yourself what you would change print Test() to.
I think i know what you are trying to do, try changing your Test function:
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT + LastNameT
else:
first_username = ForeNameT + MiddleNameT + LastNameT
return first_username
notice the changes to the variable names vs. the function names and the return value so print has something to actually print

Categories