Program keeps displaying None even after input - python

The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())

At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()

Related

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

How can i change the login from an external file to a loop?

I would like to read the credentials from the external file into a loop, so every time the password is incorrect it will ask me once again.
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split() # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
Simply do this:
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
with open("accountfile.txt","a") as file:
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
log = 0
while log != 1:
if login():
log = 1
print("You are now logged in...")
else:
log = 0
print("You aren't logged in! Please try again...\n")

Checking to see if username already exists

Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see scores:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for loging in!")
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
login_user()
The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
...
What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.
What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.
Here's what should work for you:
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
else:
print("This username is already taken. Please try another.")
if goodlogin2 = True:
print("Ok, please continue!")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
...
It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration.
Try this instead:
# If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print("Ok, please continue!")
# for id in range(len(usernameslist)):
# if newusername != usernameslist[id]:
# goodlogin2 = True
# print("Ok, please continue!")
# else:
# print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
This produces the following output for a user with no previous account who enters a name which has not been used:
--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username:

python read/write to file login script

I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()

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