Error with referenced before assignment in python - python

I am trying to create a login and register program in simple console python, however when trying to make a loop that will check if the username contains a digit I keep getting the error, ("UnboundLocalError: local variable 'includesDigit' referenced before assignment") the code is:
def register():
incluesDigit = False
print("")
print("Create Account")
print("~~~~~~~~~~~~~~")
print("Username: ")
registerUsername = input("")
for char in registerUsername:
if char.isdigit():
includesDigit = True
if includesDigit == True:
print("Please enter a username that does not contain a number")
register()
print("Password: ")
registerPassword = input("")
if len(registerPassword) < 5:
print("Please enter a password that is atleast 5 characters")
register()
if len(registerPassword) > 15:
print("Please enter a password that is less than or fifteen character")
logCreate = open("C:\\Desktop\\Login Program\\Accounts\\" + registerUsername + ".txt", "w")
logCreate.write(registerPassword)
logCreate.close()
login()

There is a typo in line 2.
incluesDigit = False
Should be
includesDigit = False

Related

Having trouble preventing users from registering with a duplicate username on Python

I'm a student who is doing my Python assignment. Thing is, our lecturer is really strict on us not using python built ins and also refuses to check our code before submission and I'm having the hardest time trying to get my code to work properly during registration.
My problem currently is that I want the code to prompt an error from the program itself when the user tries to register with a taken username. However, it keeps running different errors regardless of how I try to fix it. Can anyone please point me in the right direction or tell me what's wrong with my code? I'd be really grateful for any help.
def grant():
print("Helllooooo")
def begin():
while True:
print("Welcome to the Freshco Groceries App!")
option = input("Are you a new or returning user?\n"
"Enter 1 if you would like to LOGIN\n"
"Enter 2 if you would like to register\n"
"Enter 3 if you would like to exit the program\n")
if option=="1":
access(option)
break
elif option=="2":
access(option)
break
elif option=="3":
print("Thank you! Have a good day.")
exit()
else:
continue
def access(option):
if(option=="1"):
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
login(name,password)
else:
print("First step: Please choose a username and a unique password.")
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
register(name,password)
newuser()
def login(name,password):
success=False
file = open("user_details.txt","r")
for line in file:
a,b = line.split(",")
if (name in a) and (password in b):
success=True
break
file.close()
if(success):
print("You have successfully logged in! Happy shopping!")
grant()
else:
print("Wrong username or password entered.")
def register(name,password):
exist = False
while True:
file = open("user_details.txt", "r")
for line in file:
line = line.rstrip()
if (name == line):
exist = True
break
else:
pass
file.close()
if (exist):
print("Username has been taken. Please try again with a new one.")
break
else:
file = open("user_details.txt","a")
file.write("\n" + name + "," + password)
print("You have successfully registered! Welcome to the Freshco Family!")
grant()
break
def newuser():
print("Before you start using the app, please fill in the details below.")
alldata = []
while True:
newdata = []
nname = input("Please enter your full name:\n")
newdata.append(nname)
while True:
ngender = input("Are you female or male?\n"
"1: female\n"
"2: male\n")
if ngender=="1":
fingender="female"
newdata.append(fingender)
break
elif ngender=="2":
fingender="male"
newdata.append(fingender)
break
else:
print("INVALID INPUT")
continue
naddress = input("Please enter your address:\n")
newdata.append(naddress)
nemail = input("Please enter your email address:\n")
newdata.append(nemail)
ncontact = input("Please enter your contact number:\n")
newdata.append(ncontact)
ndob = input("Please enter your dob in this format: <DD.MM.YY>\n")
newdata.append(ndob)
alldata.append(newdata)
print(newdata)
break
print("Thank you for entering your information, you will be redirected now!")
grant()
begin()
thank you so much! T-T

Function that iterates over text file

I'm a total newbie to programming and have just begun my first project which is a simple login app.
So far my code looks like this:
def login_or_registration():
user_choice = input("Login (L) or Registration (R)? ").lower()
if user_choice == "l":
print("You will be redirected to the login window.")
login()
elif user_choice == "r":
print("You will be redirected to the registration window.")
registration()
else:
print("Invalid choice.")
def registration():
name = input("Name: ")
surname = input("Surname: ")
username = input("Username: ")
pass1 = input("Password: ")
pass2 = input("Repeat password: ")
if pass1 != pass2:
print("Passwords don't match!")
email = input("E-mail: ")
age = input("Age: ")
while True:
if not age.isdecimal():
print("Please enter a number.")
if not name.isalpha():
print("Please use only letters for Name and Surname.")
if not surname.isalpha():
print("Please use only letters for Name and Surname.")
break
with open("userbase.txt", "a") as f:
f.write(username + "\n" + pass1 + "\n" + surname + "\n" + name + "\n" + email + "\n" + age + "\n" + "\n")
f.close()
user_choice = input("Would you like to log in now? (Y/N) ").lower()
if user_choice == "y":
login()
else:
"Quitting."
def login():
logged_in = False
username = input("USERNAME: ")
password = input("PASSWORD: ")
while logged_in == False:
f = open("userbase.txt", "r")
for line in f:
if line == username:
logged_in = True
print("Logged in!")
print("User not found!")
login_or_registration()
I know its incomplete and messy but for now i want to work on a function for logging in. My idea was to create a function that would iterate over a text file and search for a match to the users input I know it's not perfect and could have many problems but for now I want to avoid modules. I wrote the function login() but it doesn't work and I don't have an idea how to make it run. My idea was to make an if statement that would be checked for every iteration of a for loop inside a while loop combined with a boolean that would be set to True after the statement is true.

Unable to compare input variable to data within a .txt / Unable to read file to compare data

Currently I'm in the process of making a program where you can both login and register and the username/password are stored in a separate .txt file.
Registering is working fine, the username and password is written without issue but I am having issues with reading from the file in both userRegister and userLogin
The .txt file is formatted by username,password and I was wondering how I would go about reading from the file with the intention of comparing loginUsername and loginPassword to username_password and comparing registerUsername to existing usernames to ensure there are no duplicates.
username_password = open("savedCredentials.txt", "r+")
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
registerPassword()
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
username_password.close()
A few things:
You aren't calling any functions in your above code, so nothing will run as it stands.
You cannot iterate a Text wrapper, you can get around this by just reading your file by .read()
If you close() the file outside of your functions, you'll get an error that the file is closed, close the file within your function instead (whenever the user is done).
It appears once you go through the conditional if search, the .read() doesn't work anymore for the 2nd round. Don't quite know why (maybe someone else here can go into more detail), but the workaround is instead convert your file to a list, and search through that instead.
The below works, but it is a bit ugly (I have to go know, but wanted to post this real quick so you have at least a working example, and can build off of it).
username_password2=[]
with open("savedCredentials.txt", "r+") as file:
for lines in file:
a=lines.replace(',',' ')
b=a.split()
username_password2.append(b)
username_password = [x for y in username_password2 for x in y]
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
while True:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
register.close()
break
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print(username_password)
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
startMenu()
You have to add the read function to your file opening.
replace the line username_password = open("savedCredentials.txt", "r+")
by
username_password = open("savedCredentials.txt", "r+").read()
then you have to remove the line username_password.close()
also, you need to call your startMenu function so add startMenu() at the bottom of your code.

How to fix unknown login after multiple atemps

When I log in as an "existing user", it works perfectly when I log in first try
But in the while loop, when I get the login incorrect and it prompts me again and THEN I get the login correct, it comes up as login failed
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
I expect the output for the login to be successful, but it says incorrect unlike when I get it right the first try
After Python has read a file, its "Prompt" is at the end of the file. If you do call read on the fileobject again it will return nothin since there is nothing left to read.
With seek(x) you can place the "Prompt" to the postion x. In you case 0 since you want to read the file again.
I injected the line on the right place:
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
accountFileR.seek(0) # <---- injected line
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()

Code will only read the first line of a text file

So I copied some code over from another post on here, but i cant get it to read any lines after the first, im trying to make a username and password system.
def register(): #This function has been adapted from www.stackoverflow.com
print("Please register.")
time.sleep(1)
username = input("Please input your desired username: ")
password = input("Please input your desired password: ")
file = open("outputusernamefile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
print("Please login now.")
time.sleep(1)
logged = True
login()
def login(): #This function has been adapted from www.stackoverflow.com
print("Please enter your credentials.")
time.sleep(1)
login.username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))
for line in open("outputusernamefile.txt","r+").readlines(): # Read the lines
login_info = line.split() # Split on the space, and store the results in a list of two strings
if login.username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
print("You are now logged in.")
logged = True
QuizStart()
return True
else:
print("Incorrect credentials.")
print("Please try again.")
time.sleep(0.5)
login()
return False
You're quitting the loop in the very first iteration. That's why only one line is being checked. Perhaps try to do something like this.
def login():
...
with open("outputusernamefile.txt","r+") as file:
for line in file.readlines():
login_info = line.split() # Split on the space, and store the results in a list of two strings
if login.username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
print("You are now logged in.")
logged = True
QuizStart()
return True
print("Incorrect credentials.")
print("Please try again.")
time.sleep(0.5)
login()
The recursive call in the login function starts reading the file from the beginning because the file is opened again.
You need to read the entire file, searching for a match, and then make the final decision at the end of the loop. You can only return early if the function finds the requested user name.
Here's how it works for me. You forgot to iterate over the lines one by one.
import time
def register(): #This function has been adapted from www.stackoverflow.com
print("Please register.")
time.sleep(1)
username = input("Please input your desired username: ")
file = open("outputusernamefile.txt","a")
file.write(username)
file.write(" ")
password = input("Please input your desired password: ")
file.write(password)
file.write("\n")
file.close()
print("Please login now.")
time.sleep(1)
logged = True
login()
def login(): #This function has been adapted from www.stackoverflow.com
print("Please enter your credentials.")
time.sleep(1)
login.username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))
with open("outputusernamefile.txt","r+") as file: # Read the lines
line = file.readline()
while line:
login_info = line.split() # Split on the space, and store the results in a list of two strings
if login.username == login_info[0] and password == login_info[1]:
user_found = True
print("QuizStart()")
return True
else:
time.sleep(0.5)
user_found = False
line = file.readline()
if not user_found:
print("Incorrect credentials.")
print("Please try again.")
login()
else:
print("Correct credentials!")
print("You are now logged in.")
register()

Categories