I'm a beginner in coding and I need to do an assignment- I've tried to do the above task as planned but all I ended up doing was verifying a username. The task is for Player 2 and Player 2 to enter a username and password. If password is correct then the game starts- but I don't know how to start the game. Keeping in mind I'm just a ks3/GCSE student so my code will not be very high-level. Please may I have some help? Thank you!
you can create a function around the game code. Than you add in over the function
username = input("Enter Username: ")
password = input("Enter password")
if username == Username and password == Password:
game()
Related
So basically what this code is supposed to do is to be a login page. It asks wether if the user has an account or not ( in my case the user doesn't have an account ). The user creates an account ( this part works ) but the user info is not saved in the txt file. I looked at other sites and youtube videos that explain this topic, but none of them work. Visual Studio doesn't give me an error but when I open the txt file, the info is not shown. Also, I work on a mac ( don't know if it will matter ).
def main_menu():
OPTION = input("Do you have an account? (yes/no)\n")
if OPTION == "yes":
login()
if OPTION == "no":
register()
def register():
USERNAME = input("Create your username: \n")
PASSWORD = input("Create your password: \n")
database = open("databse.txt", "w")
database.write(USERNAME)
database.write(PASSWORD)
database.close()
PASSWORD_CHECK = input("Confirm your password: \n")
if PASSWORD_CHECK != PASSWORD:
print("Your passwords do not match. Try again. \n")
register()
if PASSWORD_CHECK == PASSWORD:
print("You have successfully created an account! Welcome!")
# another menu here
def login():
pass
main_menu()
I've seemed to create a bank account log in system that works correctly. The only problem is that once a login is successful, the program would get stuck in a loop. For example: Say, I create my account and set my username as "Hello" and my password as "123".
The program will except these log in details but when I later try to log in with them, the infinite loop would happen.
I've tried amending this problem by plugging in return/global values for status and even put them in as many places in my program as possible but the infinite loop problem still persists. Could you please help me find why the loop keeps executing?
users = {}
status = ""
#--------------- Login menu -----------------#
def displayMenu():
global status
status = input("Are you a registered user? \n1 - Yes \n2 - No \nQ - Quit \n")
if status == '1':
oldUser()
elif status == '2':
newUser()
return status
def mainMenu():
print("Hello account holder", login,"what service would you like to use today?")
#---------- Screen for new users -------------#
def newUser():
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nAccount created!\n")
#---------- Screen for old users -------------#
def oldUser():
global login
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print("\nLogin successful!\n")
mainMenu()
else:
print("\nUser doesn't exist or wrong password!\n")
# Main -------------------------------------------------------------------------------------------------------------
while status != "q":
status = displayMenu()
Your code is working exactly as it is designed.
The main loop starts:
while status != "q":
status = displayMenu()
Note that your program will only ever "quit" if the user gives an input of "q" in the displayMenu(), rather than "Q". This can be fixed by checking status.lower() instead.
Then you specify that no, you are not a registered user by providing 2 as an input to the displayMenu().
This brings you to newUser(), where you create your new account.
You'll then get returned to displayMenu(), where you can this time select 1 to login as a registered user, bringing you to oldUser().
Once you enter your login credentials in oldUser(), you'll get brought to mainMenu(), where it will print the welcome message in mainMenu(), then return to oldUser(), then to displayMenu(), then back to the main loop.
Unless you're expecting something else to happen in mainMenu(), the only error here is that you're not normalizing the case of status before checking if it is "q".
My assessment is to construct a password vault, with basic python lists, functions while loops, etc, but am having issues on the part where the user actually inputs passwords for their apps. The first problem is when they ask to see their passwords and don't have any it should say "you have nothing stored", it says this but don't stop repeating it, and also wondered if I could get some help on completing the rest of it. here is what I would like this part of the code to look like in terms of using it.
Press: 1) find your existing passwords 2) save a new password for your apps
3) see a summary of your password locker 4) exit password locker successfully
2
Name of website: Facebook
Username of site: bob91
password of site: bob95
would you like to add another app: yes
Name of website: Instagram
Username of site: albert91
password of site: albert95
would you like to add another app: no
Press: 1) find your existing passwords 2) save a new password for your apps
3) see a summary of your password locker 4) exit password locker successfully
1
Which app password would you like to access: Facebook
Facebook
username: bob91
password: bob95
-------------------------------------------------- My actual code right now -->
vault_apps = []
app_name = ""
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
while True:
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locke \n4) exit password locker successfully
---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
if locker_menu_var == "1":
while len(vault_apps) < 1:
print('''you have nothing stored''')
break
break
elif locker_menu_var == "2":
app_name = input('''
What is the name of the website/app your are adding?
''')
app_password = input('''What is the password of your {} account?
'''.format(app_name))
vault_apps.append([app_name, app_password])
while True: another_app = input('''Would you like to add another app to your password locker?''')
if another_app in {"Y", "YES"}:
print("okay")
break
break
locker_menu_func()
I used dictionary to store the password. Try it this way. If it solved your problem, Kindly upvote and make it as a answer.
app_passwords = {}
def locker_menu_func():
print('''You have opened the locker,
Please select what you would like to do,''')
while True:
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locke \n4) exit password locker successfully''')
if locker_menu_var == "1":
while len(app_passwords) < 1:
print('''you hve nothing stored''')
break
else:
for kv in app_passwords.items():
a= kv[0],kv[1]
print(str(a).replace("(","").replace(")","").replace("[","").replace("]",""))
#print (app_passwords)
elif locker_menu_var == "2":
web = input("Enter Website")
username = input("Enter username")
password = input("Enter password")
app_passwords[web]=["username:"+username+","+"password:"+password]
elif locker_menu_var == "3":
print ("Count of Websites stored",len(app_passwords))
elif locker_menu_var == "4":
break
locker_menu_func()
Just started learning python a couple days ago and have been trying to use what code I know to practice a basic code of asking for a user name and password from a list. I know there are far better/cleaner/matching user to password inputs but I'm just playing with what I know at this point.
users = ['Jon','Joe', 'Jole']
user_input = input('Username: ')
while user_input != users:
user_redo = input("I'm sorry but we dont recognize you. Please try another username: ")
this is where my problem is. Is there a simple way of breaking the loop if the user enters a matching username from the list?
passwords = ['donkey808','Hanna5006']
password = input('Password: ')
I guess the same question would apply to the password entry as well
while password != passwords:
pw_redo = input(f'Please enter correct password for user {user_input}: ')
else:
print(f'Access Granted {user_input}')
Write it like this.
users = ["Jon","Joe", "Jole"]
while 0 < 1 :
user_input = input('Username: ')
if user_input not in users:
print("I'm sorry but we dont recognize you. Please try another username: ")
elif user_input in users:
break
Just do while user_input not in users:
not in checks if user_input is literally not in users
It might also be better to do if user_input not in users:, I don't see the point of a while.
I am trying to create a simple login system. What I'm doing is storing the login data in a text file called 'accounts.txt'
Now, when user tires to login, it first checks if the username given by the user is in the 'accounts.txt'. If it exists, then it asks for the password and then checks if password matches with the password in 'accounts.txt'
fr = open('accounts.txt', 'r')
while True:
username = input('Enter your username: ') # Ask for their username
if username in fr.read(): # Check if username exists
password = input('Enter password: ') # Ask for password if username exists
if username+password in fr.read():
print('Welcome ' + username)
break
else:
print('Wrong password')
Note, the password save in accounts.txt is in the format of usernamepassword so if username is jack and password is gate, the actual password in the txt file will be jackgate, hence im using username+password to check if password is correct.
The problem occuring is if the user enters correct username, then program moves ahead properly but even if the password entered is right, it still displays 'Wrong password' .When the second time user enters username, it even shows error for wrong username. I tried to play with the code for a long time but couldn't come up with a solution. I guess it has something to do with fr.read(). Can I use that 'fr' object only once?
Let me suggest some improvements with my answer to your question. I would read the accounts file in its entirety so you have an in-memory structure. If you do this as a dictionary in the form accounts[USER] -> PASS you can easily check for any account as per the code below.
Regarding my suggestions (they do not exactly only answer your questions, but IMHO the topic of writing login code should be treated with care):
I strongly recommend not to store passwords in plain text, regardless of application importance, always use hashes.
Do not store just the password hash, always use salting.
Do not tell the person trying to log in, if the username or the password was wrong, always just say "that's not the right combination", thus making it harder to break in.
Please find information about hashing functions in Python here: https://docs.python.org/3/library/hashlib.html#randomized-hashing
This site has a good introduction on salting ans securing passwords: https://crackstation.net/hashing-security.htm
Do you users a favor and treat the username as no case-sensitive. That is a totally valid approach, but it annoys me every time I have to use such a site (just like email addr are not case-sensitive)
As I am a total layman regarding password security, maybe one of the other Stackoverflow users can jump in with a comment and expand on this topic.
Anyway, here is my answer for your question on how to check for a login. I created a function check_account() that returns True or False, depending on wether the supplied credentials were correct or not.
import hashlib
import os
import binascii
def check_account(usr, pwd):
# read the accounts file, a simple CSV where
# username, salt value and password hash are
# stored in three columns separated by a pipe char
accounts = {}
fr = open('/users/armin/temp/test.csv', 'r')
for line in [x.strip().split("|") for x in fr.readlines()]:
accounts[line[0].lower()] = (line[1], line[2])
fr.close()
# now go looking if we do have the user account
# in the dictionary
if usr in accounts:
credentials = accounts[usr]
# credentials is a list with salt at index 0
# and pwd hash at index 1
# generate the hash form the functions parameters
# and compare with our account
h = hashlib.blake2b(salt=binascii.unhexlify(credentials[0]))
h.update(pwd.encode('utf-8'))
if credentials[1] == h.hexdigest():
return True
else:
return False
else:
return False
def main():
while True:
username = input('Enter your username: ') # Ask for their username
password = input('Enter password: ') # Ask for password if username exists
if check_account(username.lower(), password):
print("Welcome, {0}".format(username))
else:
print('Username or password unknown')
if __name__ == '__main__':
main()
To create the data for a user account, use may this code.
def create():
username = input('Enter your username: ').lower() # Ask for their username
password = input('Enter password: ') # Ask for password if username exists
salt = binascii.hexlify(os.urandom(hashlib.blake2b.SALT_SIZE))
print("SALT value:", salt)
h = hashlib.blake2b(salt=binascii.unhexlify(salt))
h.update(password.encode('utf-8'))
print("Pwd hash:", h.hexdigest())
You can use startswith and endswith:
fr = [i.strip('\n') for i in open('accounts.txt')]
while True:
username = input()
if any(i.startswith(username) for i in fr):
password = input('Enter password: ')
if any(username+password == i for i in fr):
print("welcome")
break
else:
print("wrong password")
I would do
if password in fr.read():
instead of
if username+password in fr.read():
This is because for it to get to the if password in fr.read loop it first has to pass the if username in fr.read loop. However, the only problem I find with this is that if they enter a correct username but enter the wrong password for that username but correct password for another username it will still pass.
That is why I think you should use a dictionary not a text file.
For example, if the usernames allowed is username and username1 and the password is username and username1, then in a different .py file, you can say.
username_password={'username':'username','username1':'username1'}
that makes a dictionary that has the username and passwords.
let's say you name that file stuff.py. Then in the second file that has to be in the same directory, you can do
from stuff import * #imports all values from stuff.py
while True:
username = input('Enter your username: ') #gets username
if username_password.has_key(username):
password = input('Enter password: ')
if password== username_password[username]:
print('Welcome '+username)
break
else:
print('Wrong password')
break
else:
print('Wrong username')
I still don't get why you have a while loop, but if you want it, it is fine. Also, I added an else loop just in case the username is wrong.