Could anyone please assist me with the following:
I have a code that reads a username and password then allows users to access a program. I have the first option to register a new user correct. I'm having a problem with an infinite loop problem with my last two lines of code. Id like to run a string stating that if an unregistered username is entered it returns with a string saying that there is no such registered user. The string just keeps running in the loop and is there anything I could do to change this.
username: admin
password: adm1n
my code is as follows:
users = {}
with open ('user.txt', 'rt')as username:
for line in username:
username, password = line.split(",")
users[username.strip()] = password.strip() # strip removes leading/trailing whitespaces
uinput = input("Please enter your username:\n")
while uinput not in users:
print("Username incorrect.")
uinput = input("Please enter a valid username:/n")
if uinput in users:
print ("Username correct")
with open('user.txt', 'rt') as password:
for line in password:
username, password = line.split(",")
users[password.strip()] = username.strip() # strip removes leading/trailing whitespaces
uinput2 = input("Please enter your password:\n")
while uinput2 not in users:
print("Your username is correct but your password is incorrect.")
uinput2 = input("Please enter a valid password:\n")
if uinput2 in users:
password2 = ("Password correct")
print (password2)
if password2 == ("Password correct"):
menu = (input("\nPlease select one of the following options:\nr - register user\na - add task\nva - view all tasks\nvm - view my tasks\ne - exit\n"))
if menu == "r" or menu == "R":
new_user = (input("Please enter a new user name:\n"))
new_password = (input("Please enter a new password:\n"))
with open ('user.txt', 'a')as username:
username.write("\n" + new_user + ", " + new_password)
elif menu == "a" or menu == "A":
task = input("Please enter the username of the person the task is asigned to.\n")
while task not in username:
print("User not registered. Please enter a valid username:\n")
You have a loop at the end that says
while task not in username:
print("User not registered. Please enter a valid username:\n")
This is unfinished and will loop endlessly since if task is not in username, printing something will not change that fact so it will just loop and print again. You probably wanted to add something like
task = input("Please enter a valid username of a person the task is assigned to.\n")
Related
I'm trying to create a simple new user registration function. There should be a process for assessing new usernames entered by the user which checks for duplicates in an external file and rejects them. The file user.txt is simply a line-by-line list of usernames and passwords separated by a comma.
Problem: the code keeps ignoring my effort to match each new user input variable user with the usernames stored in the text file (line[0])
The contents of "user.txt" is as follows:
admin, admin
admin1, admin1
admin2, admin2
etc.
Any help appreciated thanks
def reg_user():
if username == "admin" and login == True:
registry = open("user.txt", "r+")
# Requests username and prevents duplicates
for line in registry:
line = line.split(", ")
while registry:
user = input("Please enter a username to register:\n")
if user == line[0]:
print("Sorry, that username is taken. Try a different one.")
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = registry.write("\n" + user + ", " + password)
registry.close()
Something like this should work:
username = 'admin'
login = True
if username == "admin" and login == True:
file = open("user.txt", "r+")
registry = file.read().split('\n')
# Requests username and prevents duplicates
ok = False
while not ok:
user = input("Please enter a username to register:\n")
ok = True
for line in registry:
if user == line.split(', ')[0]:
print("Sorry, that username is taken. Try a different one.")
ok = False
password = input("Please enter a password to register:\n")
passcheck = input("Please re-enter your password:\n")
if password != passcheck:
print("Your password doesn't match. Please re-enter your password.")
else:
print("Thanks. You're registered")
user = file.write("\n" + user + ", " + password)
file.close()
user.txt file:
a, foo
e, pass
Example interaction:
Please enter a username to register:
a
Sorry, that username is taken. Try a different one.
Please enter a username to register:
e
Sorry, that username is taken. Try a different one.
Please enter a username to register:
f
Please enter a password to register:
pass1
Please re-enter your password:
pass1
Thanks. You're registered
I had to write a program in python that can add/write 'users' and 'tasks' to a .txt file.
I have done all that and everything works as needed.
I now have to do the following and this is where I'm stuck.
I have to format the program so that:
Only the user with the username 'admin' is allowed to register(make use of the 'r' option) new users.
Note: admin user is saved in users.txt as: admin(username), adm1n(password)
The admin user is provided with a new menu option that allows them to display statistics. When this menu option is selected, the total number of tasks and the total number of users should be displayed in a user-friendly manner.
Here is my code:
users = {}
with open ('user.txt', 'rt')as username:
for line in username:
username, password = line.split(", ")
users[username.strip()] = password.strip() # strip removes leading/trailing whitespaces.
user_username = input("Please enter your username: ")
while user_username not in users:
print("The username is incorrect.")
user_username = input("Please enter a valid username: ")
if user_username in users:
print ("The username is correct.")
with open('user.txt', 'rt') as password:
for line in password:
username, password = line.split(", ")
users[password.strip()] = username.strip() # strip removes leading/trailing whitespaces.
user_password = input("Please enter your password: ")
while user_password not in users:
print("Your username is correct but your password is incorrect.")
user_password = input("Please enter a valid password: ")
if user_password in users:
password2 = ("Your password is correct.")
print (password2)
if password2 == ("Your password is correct."):
# Give the user options to proceed.
user_options = input("""
Please select one of the following options:
r - register a user
a - add a task
va - view all tasks
vm - view my tasks
e - exit
""")
if user_options == "r":
new_user = (input("Please enter a new user name: "))
new_user_password = (input("Please enter a new password: "))
new_password = False
while new_password == False: # Add a 'while loop' untill the condition is met(True).
confirm_new_password = input("Please retype your password to confirm: ")
if new_user_password == confirm_new_password:
new_password = True
elif new_password == False:
print("Your passwords do not match!")
with open ('user.txt', 'a')as user_file:
user_file.write(f"\n{new_user}, {new_user_password}")
# Add a task to a specific user.
elif user_options == "a":
task_file = open("tasks.txt", "a+")
new_task_username = input("Please enter the 'username' of the person this task will be assigned
to: ")
new_task_tile = input("Please enter the 'tile' of the new task: ")
new_task_description = input("Please give a brief description of the new task:\n")
new_task_due_date = input("""Please enter the due date of the given task, in the following
format;
dd-mm-yyyy:\n""")
new_task_completed = input("Is the new task completed (Yes / No): ")
task_file.write(f"\n{new_task_username}, {new_task_tile}, {new_task_description},
{new_task_due_date}, {new_task_completed}")
task_file.close()
# View all tasks.
# NOTE: You have to add tasks first before you can view all tasks.
elif user_options == "va":
task_file = open("tasks.txt", "r")
for line in task_file:
new_task_username, new_task_tile, new_task_description, new_task_due_date, new_task_completed = line.split(", ")
print(f"""
New task username: {new_task_username}
Task tile: {new_task_tile}
Task description: {new_task_description}
Task due date: {new_task_due_date}
Task completion: {new_task_completed}
""")
task_file.close()
# View task assigned to a user.
elif user_options == "vm":
with open("tasks.txt", "r") as task_file:
for line in task_file:
new_task_username, new_task_tile, new_task_description, new_task_due_date,
new_task_completed = line.split(", ")
if user_username == new_task_username:
print(f"""
New task username: {new_task_username}
Task tile: {new_task_tile}
Task description: {new_task_description}
Task due date: {new_task_due_date}
Task completion: {new_task_completed}
""")
elif user_options == "e":
exit
else:
print("Invalid selection! Please choose a valid option.")
This worked for me:
if user_options == "r": # Only the user logged in as 'admin', will be able to access this menu.
if user_username != "admin":
print ("You are not an admin user, only admin can register new users.")
elif user_username == "admin":
# Create a new menu to display for admin.
admin_menu = (input("""
Please select one of the following options:
r - register a new user
d - display statistics = Total number of tasks & users
e - exit
"""))
if admin_menu == "r":
new_user = (input("Please enter a new user name: "))
new_user_password = (input("Please enter a new password: "))
new_password = False
while new_password == False: # Add a 'while loop' untill the condition is met(True).
confirm_new_password = input("Please retype your password to confirm: ")
if new_user_password == confirm_new_password:
new_password = True
elif new_password == False:
print("Your passwords do not match!")
with open ('user.txt', 'a')as user_file:
user_file.write(f"\n{new_user}, {new_user_password}")
elif admin_menu == "d":
# These varibles will only count the lines inside the 'txt' files,
# but since we are storing every new task & user on a new line,
# we can just count the lines for the desired results.
tasks_num = 0
users_num = 0
with open("tasks.txt", "r") as task_file:
for line in task_file:
tasks_num += 1
print (f"\nTotal number of tasks: {tasks_num}")
with open("user.txt", "r") as username:
for line in username:
users_num += 1
print (f"Total number of users: {users_num}")
elif admin_menu == "e":
exit
I need to be able to validate the user and the password inputted, but when I run the code below, I'm able to verify only the first element of the list and the second element and so on aren't being verified.
Note: The user and password are stored in the list as class objects [like this:
admin(user, password)]...
def login(self):
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
for obj in self.admins:
while obj.admin_name != user_name and obj.admin_password != password:
print(" Sorry Username and Password Incorrect Please Re-enter for Validation ")
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
else:
print("Greetings,", user_name, "You are Now Logged in the System")
break
When you run break in your else branch you are actually calling it on the for loop. Remove the break and it should be working as you expect it to
Your while loop only checks for the first user name. You should switch the order of your loops:
def login(self):
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
while True:
for obj in self.admins:
if obj.admin_name == user_name and obj.admin_password == password:
break
else:
print(" Sorry Username and Password Incorrect Please Re-enter for Validation ")
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
continue
break
print("Greetings,", user_name, "You are Now Logged in the System")
This is also a very bad way to check passwords.
Simply remove break from your else statement.
The issue I keep having is that after I register a username/password, then try to login if I get any letters or numbers of the login/password correct it accepts it, for example if my username is Fof and my Password is tog and I enter the username as just f or o it will accept it.
Here's the code written in Python idle 3.7:
if Game == "1":
username = input("Please enter your username: ")
if username in open("Names.txt").read(): #fix
print ("Welcome " + username)
password = input("Please enter your password: ")
if password in open("Passwords.txt").read():
print ("success!")
else:
print("Username incorrect!")
An explanation of what you need:
You need to look for the exact match of the word in the file, not just in because that would always return True and hence it would bypass:
An example:
NamesList:
Fof
Abc
Def
and then:
import re
text = input("enter Name to be searched:")
NamesFile = open("NamesList.txt", "r")
for line in NamesFile:
if re.search(r"\b" + text + r"\b", line):
print(line)
else:
print("Name not found")
break
OUTPUT:
enter Name to be searched:Fof
Fof
In another case:
enter Name to be searched:f
Name not found
If you store logins and passwords the way you do, then one user can use password of another user and vice versa. It's better to store login-password pair together:
File credentials.json:
{"Fof": "tog"}
Code:
import json
with open('credentials.json') as f:
credentials = json.load(f)
username = input('Please enter your username: ')
if credentials.get(username):
print('Welcome {}'.format(username))
password = input('Please enter your password: ')
if credentials[username] == password:
print('success!')
else:
print('Username incorrect!')
Let's try to hack:
Please enter your username: f
Username incorrect!
Successful login:
Please enter your username: Fof
Welcome Fof
Please enter your password: tog
success!
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()