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.
Related
from time import sleep
import time
users = {}
status = ""
def loading():
spaces = 0
while spaces < 3:
print("Loading" + "." + " " + "." + " " + "." + " " + "." + " " )
spaces = spaces + 1
sleep(1)
def mainMenu():
global status
status = input("Do you have a login account? y/n Or press q to quit\n")
if status == "y":
oldUser()
elif status == "n":
newUser()
elif status == "q":
quit()
#Creating function for new user account creation
def newUser():
createUser = input("Please create a username: ")
for line in open(r"C:\Users\User\Desktop\Python Project\accountdetails.txt", "r").readlines():
user_info = line.split()
createdUser = user_info[0]
if createUser in createdUser:
print("\nUsername already exist!\n")
else:
createPass = input("Please type a new password: ")
users[createUser] = createPass
print("\nAccount Created\n")
login = open(r"C:\Users\User\Desktop\Python Project\accountdetails.txt", "a")
login.write("\n" + createUser + " " + createPass + "\n")
login.close()
#Creating function for old account login
def oldUser():
userInput = input("Enter username: ")
passwInput = input("Enter password: ")
#To check if user and passw matches any existing
for line in open(r"C:\Users\User\Desktop\Python Project\accountdetails.txt", "r").readlines():
login_info = line.split()
user = login_info[0]
passw = login_info[1]
users[user] = passw
if userInput in users and users[userInput] == passwInput:
loading()
print("\nLogin Successful!\n")
sleep(1)
print(userInput, "accessed the system on:", time.asctime())
else:
print("\nUser doesn't exist or wrong password\n")
while status != "q":
mainMenu()
I am trying to check if any inputted username match within a given text file. I had this under the newUser function, however when I use the 'in' operator it doesn't help at all. I have tried to print the result of createdUser which corresponds to:
max
nicky
tom
kai
However only the result which is kai was taken into account, and if I had input other names such as max, nicky or tom, it would not indicate that the username existed.
You overwrite the variable here: createdUser = user_info[0].
Only the last value is kept as a string.
Use a list and collect all names:
def newUser():
createUser = input("Please create a username: ")
createdUser = []
for line in open(r"C:\Users\User\Desktop\Python Project\accountdetails.txt", "r").readlines():
user_info = line.split()
createdUser.append(user_info[0])
Edit: Added changes proposed by Klas, also changed variable name.
def newUser():
createUser = input("Please create a username: ")
with open(r"C:\Users\User\Desktop\Python Project\accountdetails.txt", "r") as f:
usernameSet = {line.split()[0] for line in f}
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.
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")
import sys
def intro():
print("description of quiz")
choice1 = input("press A to login and B to signup ")
choice1.lower()
if choice1 == "b":
signup()
elif choice1 == "a":
login()
else:
print("Error, invalid input")
intro()
def signup():
name = input("name ")
age = input ("age ")
year = input ("year ")
username = name[:3] + age
print("Your username is " + username + " ")
password = str(input("desired password "))
userinfo = open("userinfo.txt","a")
userinfo.write(username + "," + password + "," + name + "," + age + "," + year + "\n")
userinfo.close()
quiztype()
def login():
username1 = input("Please input your username ")
userinfo = open("userinfo.txt","r")
userinforec = userinfo.readline()
while userinforec != "":
field = userinforec.split(",")
username = field[0]
password = field[1]
name = field[2]
age = field[3]
year = field[4]
if username == username1:
password1 = str(input("What is your password? "))
if password == password1:
print("password accepted")
quiztype()
else:
print("Error, password not accepted")
login()
userinforec = userinfo.readline()#ooooooooooooooooooooooooCOME BACK TO DO THE ELSE ERROR IF USERNAMES NOT EQUALooooooooooooooooooooooooooo
userinfo.close()
def quiztype():
quiztype = input("Choose maths or history? ")
quiztype.lower()
if quiztype == "maths":
print("You have chosen maths")
difficulty()
elif quiztype == "history":
print("You have chosen history")
difficulty()
else:
print("Error, invalid input")
quiztype()
return quiztype
def difficulty():
diff = input("Choose easy, medium, or hard ")
diff.lower()
if diff == "easy":
print("You have chosen easy")
elif diff == "medium":
print("You have chosen medium")
elif diff == "hard":
print("You have chosen hard")
else:
print("Invalid input")
difficulty()
return diff
def typeoffile():
if quiztype() == "maths":
topicfile = "maths.txt"
else:
topicfile = "history.txt"
return topicfile
def questionstolist():
questionfile = open(typeoffile(),"r")
qrec = questionfile.readline()
for line in qrec:
question, rightanswer, wrong1, wrong2, wrong3, wrong4 = line.strip().split(",")#problem is here
print(question)#^problem is here^
In the function, questionstolist(), I run the code and it comes up with the following error: ValueError:need more than 1 value to unpack.
I have read up on this error and I have rectified what I thought was the error however it did not work. In my file there are 6 sections separated by commas (5+5,10,11,17,5,12) and there are 6 variables that need to be assigned.
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()