How do I create this loop? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
How do I create this loop where if welcome is not equal to "yes" or "no", it repeats the question (if they have an account), but if welcome is equal to "yes" or "no", they create an account (for "no") or allow the user to login (for "yes")?
Thanks in advance
Below is my code used :
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
if welcome == "yes":
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")

Put a loop around asking for welcome.
while True:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome in ("yes", "no"):
break
if welcome == "no":
...
else:
...

You can add a bool variable that keeps track of user's input status (valid/invalid)
validAnswer = False:
while not validAnswer:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
validAnswer = True
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
elif welcome == "yes":
validAnswer = True
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")

You can simply add a while True: to the whole thing, this way, when a "wrong" input is entered, it will fall through both of the if clauses and return to the beginning of the loop, where it will prompt the user again.
while True:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
if welcome == "yes":
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")

Related

My script can't recognise names inside the username file

It can see the file, if i change the name on the path slightly run seizes to function but eithr way it can't read the words in the file despite being able to before while I was writing the program. And now suddenly it doesn't work, the file location is the same and all.
P.S. I have no idea how to specify code on overflow
filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
def func():
user = input("Enter new Username: ")
passs = input("Enter new Password: ")
passs1 = input("Confirm password: ")
if passs != passs1:
print("Passwords do not match!")
else:
if len(passs) <= 6:
print("Your password is too short, restart:")
elif user in usern:
print("This username already exists")
else:
usern = open(filen, "a")
usern.write(user+", "+passs+"\n")
print("Success!")
while True:
if userr not in usern:
again = input("This username does not exist, would you like to try again? ")
if again == ("No"):
func()
elif again == ("no"):
func()
elif again == ("Yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif again == ("yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif userr in usern:
print("Good, you have entered the zone")
I am not sure I have full understand your means, but as your code, I have some suggestions:
close file if you open it
use f.readline() and str.split() to parse username and passwd and store in array, so you can use in to check, if the file is not to large.

I am writing some code for a login system in python and I can't seem to be able to have it read the email and password from a txt file

import hashlib
def signup():
email = input("Enter an email address: ")
pwd = input("Enter a password: ")
conf_pwd = input("Confirm your password: ")
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash1 = hashlib.sha256(enc).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "a") as f:
f.write(email + "\n")
f.write(hash1 + "\n")
f.close()
print("You have registered successfully!")
else:
print("Password is not same as above! \nPlease try again")
signup()
def login():
email = input("Enter email: ")
pwd = input("Enter password: ")
auth = pwd.encode()
auth_hash = hashlib.sha256(auth).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "r") as f:
stored_email, stored_pwd = f.read().split("\n")
f.close()
if email == stored_email and auth_hash == stored_pwd:
print("Logged in Successfully!")
else:
print("Login failed! \nPlease try again")
login()
def welcome():
print("Welcome to the [Insert Game Name Here]")
HaveAccount = input("Have you made an account before? (Y/N): ")
if HaveAccount == ("Y"):
login()
elif HaveAccount == ("N"):
signup()
else:
print("Please enter either 'Y' or 'N'")
welcome()
welcome()
It is specifically line 23 and it has a ValueError: too many values to unpack (expected 2) whenever I try and log in with an email and password. I need to add some extra text in because my post is mostly code and I don't know what else to say so here is some random typing to make more characters in my post. Any help is appreciated. Thanks

Log in is always saying it is incorrect [duplicate]

This question already has an answer here:
Searching array reports "not found" even though it's found
(1 answer)
Closed 1 year ago.
My code is always saying it is incrorrect even tough it is present on the text file,
it was working before but now isn't for some reason.
def select_login_signup():
while True:
selection = input("Welcome to sports.com, please select"
" \"L\" to Log In with your account or \"S\" to create an account: ")
if selection.lower() == 's':
register()
answer = input("Would you like to Log In? Y/N? ")
while not answer:
if answer.lower() == "y":
login()
break
elif answer.lower() == "n":
exit()
else:
answer = False
print("Invalid answer.")
continue
elif selection.lower() == 'l':
login()
break
else:
print("Invalid answer.")
continue
def register():
username = input("Create your username (no more than 10 characters or less than 4.): ")
while 10 < len(username) < 4:
print('username cannot have more than 10 characters or less than 4.')
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
while username.isnumeric():
print("username must contain at least one letter")
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
password = input("Create a password with letters and numbers: ")
while len(password) < 6:
print("Your password must contain more than 6 characters.")
password = input("Create a password with letters and numbers: ")
continue
while password.isnumeric() or password.isalpha():
print("Your password must contain both letters and numbers")
password = input("Create a password with letters and numbers: ")
continue
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "a")
login_credentials.write(f'\n{username},{password}')
login_credentials.close()
print("Account created successfully.")
def login() -> object:
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "r")
login_credentials.readlines()
with open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', 'r') as
login_credentials:
for line in login_credentials:
login_info = line.split(",")
if username == login_info[0] and password == login_info[1]:
print("Authorized")
authenticated = True
return authenticated
else:
print("Incorrect credentials.")
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
continue
def main():
select_login_signup()
if __name__ == "__main__":
main()
with open('C:\Users\hmarq\Documents\UsernameAndPassword.txt', 'r') as login_credentials
when you open a file, you have to format the data and therefore the data is not the same.
if username == login_info[0] and password == login_info[1]:
I hope it serves you, greetings.

Program doesn't print "Incorrect username or password" when writing them wrong

I'm doing a working login register program, which will write a .txt file and then confirm it to get logged in. The problem is that if I write my username and password, it doesn't print "Incorrect username or password" command if the username is wrong, it just shuts down.
print("Hello")
user = input("Do you have an account? y/n: ")
from getpass import getpass
#Function if you dont have an account
if user == "n":
while True:
username = input("Enter a username: ")
password = input("Enter a password: ")
password1 = input("Confirm your password: ")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
user = "y"
break
print("Passwords do NOT match")
#Function if you have an account
if user == "y":
while True:
username = input("Login: ")
password = getpass("Password: ")
file = open(username+".txt", "r")
data = file.readline()
file.close()
if data == username+":"+password:
print("Welcome", username)
input("Press Enter to continue")
break
print("Incorrect username or password")
As per my comment: This is because your filename is username.txt. So if you enter wrong username, it gives error FileNotFoundError. But it works expected, if you write correct username with wrong password, it gives Incorrect username or password. So you need to make a file say pass.txt, and use this for reading and writing.
user = input("Do you have an account? y/n: ")
from getpass import getpass
filename = 'pass.txt'
#Function if you dont have an account
if user == "n":
while True:
username = input("Enter a username: ")
password = input("Enter a password: ")
password1 = input("Confirm your password: ")
if password == password1:
file = open(filename, "a")
file.write(username+":"+password)
file.write("\n")
file.close()
user = "y"
break
print("Passwords do NOT match")
#Function if you have an account
if user == "y":
d = {}
with open(filename) as f:
d = dict([line.rstrip().split(':') for line in f])
while True:
username = input("Login: ")
password = getpass("Password: ")
if (username in d and d[username] == password):
print("Welcome", username)
input("Press Enter to continue")
break
print("Incorrect username or password")

How can i create a login with a text file

So I've been trying to create a quiz where you have to have an account which means you can register and login. I managed to code the register part(which i'm pretty proud of) and it saves the login details to a separate text file, when it saves the login details it looks like this: username:password
Now i'm struggling with the login part, I think you have to read the text file and then split the username and password, then I some how have to compare the inputted username and password to the saved ones.
This is what I done for the login part so far but it doesn't work:
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
Now this is how the whole code looks like(if needed):
import time
print("Welcome to my quiz")
#Creating username
def create():
print ("We will need some information from you!")
time.sleep(1)
Veri = input("Would you like to continue (yes or no): ")
def createAccount():
while True:
name = input("Enter your first name: ")
if not name.isalpha():
print("Only letters are allowed!")
else:
break
while True:
surname = input("Enter your surname: ")
if not surname.isalpha():
print("Only letters are allowed!")
else:
break
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Only numbers are allowed!")
continue
else:
break
if len(name) >= 3:
username = name[0:3]+str(age)
elif len(surname) >= 3:
username = surname[0:3]+str(age)
else:
username = input("Create a username: ")
print ("Your username is:",username)
while True:
password = input("Create a password: ")
password2 = input("Confirm your password: ")
if password != password2:
print("Password does not match!")
else:
break
account = '%s:%s\n'%(username,password)
with open ('Accounts.txt','a') as file:
file.write(account)
print ('Account saved')
if Veri == 'no':
menu()
elif Veri == 'yes':
createAccount()
else:
print ("Sorry, that was an invalid command!")
time.sleep(1)
login()
#Loging in
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
time.sleep(1)
#Choosing to log in or register
def menu():
LogOrCre = input("Select '1' to login or '2' to register: ")
if LogOrCre == '1':
login()
elif LogOrCre == '2':
create()
else:
print ("Sorry, that was an invalid command!")
menu()
menu()
If you have any ideas on how I can make the login part, that would be helpful.
You are asking for the user's username and password for every line in the accounts file. Get the inputted login information outside of the for loop.
Welcome to programming!
It can be very daunting, but keep studying and practicing. You are in the right way!
I see some points in your code that could be improved. I'm commenting below:
1) You don't need to use both open() (and close()) and with to access a file's contents. Just use with, in this case. It will make you code simpler. (A good answer about with)
2) You're asking for the user login & passwd inside a loop (aka multiple times). It can be very annoying for your user. Move the input's call to before the for loop.
3) You also need to break the loop when the login succeeds.
So, a slightly improved version of your code would be:
filename = 'Accounts.txt'
with open(filename, 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter password: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
print("User or password is incorrect!")
Not sure what is not working in your code, but I updated the code as below and was able to print logged in.
def login():
#filename = 'Accounts.txt'
#openfile = open('Accounts.txt', "r")
#Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
continue
login()

Categories

Resources