read file and write to file error in python - python

well I'm getting this error when I try to use login option
"local variable 'register' referenced before assignment"
def logins():
choice = int(input("1) Do you want to Login?: \n2) Do you want to Register?: \n"))
if choice == int(2):
info = input("choose UserName: \n")
password = input("choose PassWord: \n")
register = open("D:\login\Login.txt", "r+")
register.write(info + "\n" + password)
if choice == int(1):
infos = input("choose UserName: \n")
passwords = input("choose PassWord: \n")
if register == str(infos):
print("Welcom Back! ")
#register.close()
logins()

I think this code may help you.
As you use register variable in both case, then you can defined this variable outside the if statement.
def logins():
choice = int(input("1) Do you want to Login?: \n2) Do you want to Register?: \n"))
register = open("D:\login\Login.txt", "r+")
if choice == 2: # 2 is already int no need to change it to int.
info = input("choose UserName: \n")
password = input("choose PassWord: \n")
register.write(info + "\n" + password)
if choice == 1: # 1 is already int no need to change it to int.
infos = input("choose UserName: \n")
passwords = input("choose PassWord: \n")
if register == str(infos):
print("Welcom Back! ")
register.close()
logins()

Related

How do i get this code to work? login/register program in python with dictionary and functions

login_input = {"MEK1300":"Python"}
username = {}
user = input("To login enter Yes. If you want to register enter No: ")
def login_info():
if user == "Yes":
login_user()
else:
user == "No"
register_user()
return user
def register_user():
new_user = input("Enter a username: ")
if new_user in login_input:
print("Your username already exists! ")
else:
new_password = input("Enter a password: ")
username[new_user] = new_password
print("Successful registration!")
def login_user():
login_user = input("Enter your username: ")
password = input("Enter your password: ")
if login_user in login_input and login_input[login_user] == password:
print("Successful login! ")
else:
print("Invalid username/passord. Register a new user!")
This is the beginning of a multiple choice quiz in python btw. How can i make this work? I dont want it to be to complicated.
I think youre code is fine you need to call you first fucnction to begin the quiz with login_info()
Updated code:
login_input = {"MEK1300":"Python"}
username = {}
user = input("To login enter Yes. If you want to register enter No: ")
def login_info():
if user.upper() == "YES": #Convert YeS to YES
login_user()
else:
register_user()
return user
def register_user():
new_user = input("Enter a username: ")
if new_user in login_input:
print("Your username already exists! ")
else:
new_password = input("Enter a password: ")
username[new_user] = new_password
print("Successful registration!")
def login_user():
login_user = input("Enter your username: ")
password = input("Enter your password: ")
if login_user in login_input and login_input[login_user] == password:
print("Successful login! ")
else:
print("Invalid username/passord. Register a new user!")
login_info()
You did define a login_info() function but didn't really call it in the global scope. Also, the username dictionary wouldn't be persistent. After your first run, the username will be an empty dictionary again, so the register is not working. You can try saving the username dictionary as a JSON file and reading the file when you need to rerun it.

How to make long "if" statement?

I am trying to make a long if statement where it asks you for a sign up or login, but when I get to the login part there is a syntax error. Any tips?
registration = input("Do you have a registration")
if registration == "No":
name = input("Type your name: ")
surname = input("Type your surname: ")
userp1 = name[0]+ surname.capitalize()
print(userp1)
password = input("Enter your password\n")
userInput = input("Type your login details\n")
if userInput == userp1:
userInput = input("Password?\n")
if userInput== password:
print("Welocome")
change = input("Do you want to change your username?")
if change == "No":
print("You logged in as" , userp1)
else:
userp1 = input("What would your new username be?")
print("You logged in as",userp1)
else:
print("Login")
You are writing two else statement consecutively in the last lines, and it is invalid syntax. You can put an if statement in another if statement, and you have to. This is working code but I am not sure if it is what you trying to make:
registration = input("Do you have a registration")
if registration == "No":
name = input("Type your name: ")
surname = input("Type your surname: ")
userp1 = name[0]+ surname.capitalize()
print(userp1)
password = input("Enter your password\n")
userInput = input("Type your login details\n")
if userInput == userp1:
userInput = input("Password?\n")
if userInput== password:
print("Welocome")
change = input("Do you want to change your username?")
if change == "No":
print("You logged in as" , userp1)
else:
userp1 = input("What would your new username be?")
print("You logged in as",userp1)
else:
print("Login")
Your code is not well indented. Be aware that python is sensetive to indentation.
You also don't specify what is the error you are getting.
So I take the liberty and tried to do a code that matches at maximum to your code.
Here it is:
registration = input("Do you have a registration")
if registration == "No":
name = input("Type your name: ")
surname = input("Type your surname: ")
userp1 = name[0]+ surname.capitalize()
print(userp1)
password = input("Enter your password\n")
userInput = input("Type your login details\n")
if userInput == userp1:
userInput = input("Password?\n")
if userInput== password:
print("Welocome")
change = input("Do you want to change your username?")
if change == "No":
print("You logged in as" , userp1)
else:
userp1 = input("What would your new username be?")
print("You logged in as",userp1)
else:
print("Login")

My code keeps printing a certain part of the code, instead of continuing with the rest of the program [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After I type in any username and password (doesn't matter whether it's correct or not), it keeps printing another part of the code.
The login part works fine but it doesn't show the correct output afterwards. It continuously shows:
"Incorrect login details entered
Have you made an account?
Yes or No"
This has stumped both my teacher and I. I have looked at different websites with examples of login/registration systems. I have also tried re-arranging the code differently.
This is the code:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("Usernames.txt","r")
found = False
for line in file:
user = line.split(",")
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while ans not in ("Yes", "No"):
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
elif ans == "No":
print("Would you like to make an account? ")
else:
ans = input("Please enter Yes or No ")
The expected result when the username and password is correct:
Username: Smartic
~~~~~
Welcome to the game, Smartic
The expected result when the username and password is incorrect:
Incorrect login details entered
Have you made an account?
Yes or No
The expected result when the user enters Yes:
Please sign in again
Please enter your correct username:
Please enter your correct password:
The expected result when the user enters No:
Would you like to make an account?
The expected result when the user enters something other than Yes or No:
Please enter Yes or No
No matter what username you enter, it won't satisfy every username in the file. Every time it doesn't, your error text will be printed. Reformat your code as is described in this question.
There is a new line at the end of each line in the file. You can remove newline by using strip() function.
if user[0] == username and user[1].strip() == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
Change your:
while ans not in ("Yes", "No"):
In:
while True:
Besides I can recommend to make a function.
Also as John Gordon mentioned use breaks, so your script will look like:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
user = {0:'e',1:'w'}
found = False
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while True:
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
break
elif ans == "No":
print("Would you like to make an account? ")
break
else:
ans = input("Please enter Yes or No ")
break

Python account system

I'm trying to practice because I'm doing Not Examined Assessment in school and I'm stuck with my code, it doesn't work as intended because it doesn't matter whatever I write in accnick it says that the username is correct :/
acc = input("Do you have an existing account? y/n ")
if acc == "y":
accnick= input("Enter your username. ")
while accnick in open("file.txt").read():
print("Correct username.")
accpass= input("Enter your password. ")
if len(accpass) == 0:
accpass = input("Try again. ")
while accpass in open("file.txt").read():
print("Correct password. ")
break
else:
accnick = input("Wrong username, try again. ")
elif acc == "n":
name = input("Enter your name. ")
while len(name) == 0:
name = input("You haven't entered anything, try again. ")
age = int(input("Enter your age. "))
age = str(age)
while len(age) == 0:
age = input("Enter your age again. ")
password = input("Enter your password. ")
nick = name[:3]
nickname = nick+str(age)
file=open("file.txt","w+") #w+ is to write to a file and create a file if it doesnt exist yet
file.write(name+' '+str(age)+' '+nickname+' '+' '+password)
file=open("file.txt","r")
kurwa=file.read()
print(kurwa)
name = input("Enter your name. ") ###
if 'Test Test' in open('file.txt').read():
print("Someone with that name already exists. ")
In your code it will jumpback to print("Correct username.") after a correct username was typed in. So you are stuck in a endless loop. Your break should be part of the while loop. Further I changed the second while to if.
Try this:
acc = input("Do you have an existing account? y/n")
if acc == "y":
accnick= input("Enter your username. ")
while accnick in open("file.txt").read():
print("Correct username.")
accpass= input("Enter your password. ")
if len(accpass) == 0:
accpass = input("Try again. ")
if accpass in open("file.txt").read():
print("Correct password. ")
break

Creating a program to simulate login functionality

I am trying to make a login program that compares a user's input credentials to the credentials stored in a text file.
How do I do this correctly?
This is what I have done so far:
file = open("logindata.txt", "r")
data_list = file.readlines()
file.close()
print(data_list)
for i in range(0, len(data_list)):
username = input("username: ")
password = input("password: ")
i += 1
if i % 2 == 0:
if data_list[i] == username and data_list[i + 1] == password:
print("You are successfully logged in as", username)
i == len(data_list)
elif data_list[i] == username and data_list[i + 1] != password:
print("The password you entered was incorrect, please try again.")
else: # how do i end the code if the user inputs no
if data_list[i] != username:
choice = input("The username you entered was not found, would you like to create an account? (Y/N)")
if choice.upper() == "Y":
new_username = input("new username: ")
data_list.append(new_username + "\n")
new_password = input("new password: ")
data_list.append(new_password + "\n")
file = open("logindata.txt", "w")
file.writelines(data_list)
i == data_list
This is how the credential text file is set up:
user1
pass1
user2
pass2
I think you want something like this:
def does_username_exists(username, login_file_path):
username_exists = False
user_password = None
with open(login_file_path) as login_file:
while True:
username_line = login_file.readline()
if not username_line: break
password_line = login_file.readline()
if not password_line: break
if username == username_line.strip():
username_exists = True
user_password = password_line.strip()
break
return username_exists, user_password
def main():
login_file_path = "logindata.txt"
username = input("Enter username: ")
username_exists, user_password = does_username_exists(username, login_file_path)
if not username_exists:
choice = input("The username you entered was not found, would you like to create an account? (Y/N)")
if choice.upper() == 'Y':
new_username = input("Enter new username: ")
new_password = input("Enter new password: ")
with open(login_file_path, "a") as login_file:
login_file.write(new_username + "\n")
login_file.write(new_password + "\n")
return
password = input("Enter password: ")
if not (password == user_password):
print("The password you entered was incorrect, please try again.")
else:
print("You are successfully logged in as - '{}'".format(username))
if __name__ == "__main__":
main()

Categories