So i'm trying to ask for an input and then validate if the password is correct.
It will check if the input is blank, incorrect or correct. However, after the first initial blank input, if I enter a blank again the program breaks. How do I make it keep looping and validating correctly
def getUserName():
userName = ["Chan"]
userNameInput = [""]
userNameInput[0] = input("Username: ")
while userNameInput != userName:
if userNameInput[0] == "":
print("Username can not be blank. Please try again.")
userNameInput = input("Username: ")
elif userNameInput[0] == userName[0]:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput = input("Username: ")
Why do you need lists to store the username and username input instead of just typical strings?
The reason the code fails with a string index out of range is that you set the userNameInput variable to a string instead of settings its first element to the string.
However, it would be preferable to just use strings instead of lists in the first place.
def getUserName():
userName = "Chan"
userNameInput = input("Username: ")
while userNameInput != userName:
if len(userNameInput) == 0:
print("Username can not be blank. Please try again.")
userNameInput = input("Username: ")
elif userNameInput == userName:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput = input("Username: ")
Here is a solution using strings instead of lists that solves your issue.
Repetition in programming is a bad practice. So in my solution, I have eliminated all repetition parts from your code and
def getUserName():
userName = "Chan"
while True:
userNameInput = input('Username: ')
if not userNameInput:
print("Username can not be blank. Please try again.")
elif userNameInput != userName:
print("Username is not correct. Please try again.")
else:
print("Username is correct")
break;
Output:
C:\***\****>py getUserName.py
Username: sad
Username is not correct. Please try again.
Username:
Username can not be blank. Please try again.
Username: Chan
Username is correct
The problem is that you are comparing the array index 0 however on the second time you set userNameInput it is being set to a string and not an array.
The fix would look something like this:
def getUserName():
userName = ["Chan"]
userNameInput = [""]
userNameInput[0] = input("Username: ")
while userNameInput != userName:
if userNameInput[0] == "":
print("Username can not be blank. Please try again.")
userNameInput[0] = input("Username: ")
elif userNameInput[0] == userName[0]:
print("Username is correct. Input password.")
else:
print("Username is not correct. Please try again.")
userNameInput[0] = input("Username: ")
Related
I am trying to take this code and make it so the username and password are stored in a .txt file and also hashed using MD5 for a project. I am really struggling and do not know how to incorporate that into this code. Please help, I'm desperate! Thanks!
def userName():
username = "username"
userInput = input('Please enter your username:\n')
while True:
if not userInput:
print("Your username can not be blank, please try again!\n")
userInput = input('Please enter your username.\n')
elif userInput != username:
print("Sorry, that username is not in our system. Please try again!\n")
userInput = input('Please enter your username.\n')
else:
print("Welcome back, " + username)
print("")
break
def passWord():
password = "password"
passInput = input("Please enter your password:\n")
while True:
if not passInput:
print("Your password can not be blank, please try again!\n")
passInput = input("Please enter your password.\n")
elif passInput != password:
print("Sorry, your password is invalid. Please try again!")
passInput = input("Please enter your password.\n")
else:
print("You have successfully logged in!\n")
break
def main():
print("Hello, let's get started!")
print("")
userName()
passWord()
main()
So I'm making this login system and I want new username to be added to the existing list and then save it there.
Code:
def login():
usernames = ["username1", "username2", "username3"]
passwords = ["pass1", "pass2", "pass3"]
print("Login")
username = input("Username: ")
if username not in usernames:
print("User doesn't exist")
input("Make an account? ")
if "yes":
print("Account Setup")
new_username = input("Username: ")
usernames.append(new_username)
print(usernames)
new_password = input("Password: ")
passwords.append(new_password)
print(passwords)
login()
else:
sys.exit()
else:
password = input("Password: ")
if password not in passwords:
print("Incorrect password")
login()
elif usernames[0] != passwords[0]:
print("Incorrect password")
login()
elif usernames[1] != passwords[1]:
print("Incorrect password")
login()
elif usernames[2] != passwords[2]:
print("Incorrect password")
login()
When I add new user their info is saved but when login() here is used and the login process starts again the input data is lost, the account i just created doesn't exist anymore.
if "yes":
print("Account Setup")
new_username = input("Username: ")
usernames.append(new_username)
print(usernames)
new_password = input("Password: ")
passwords.append(new_password)
print(passwords)
login()
Every time you call the login function you are setting password and username variable back to start. In this line:
usernames = ["username1", "username2", "username3"]
passwords = ["pass1", "pass2", "pass3"]
If you put those lines out of the function it will work.
BTW:
Don`t use two lists for passwords and usernames. It is inefficient and unnecessarily complicated. Use a dictionary. Like this:
logins = {"Jack": 1234, "Paul": 4321}
If you want two add new logins use:
logins["Oliver"] = 7531
If you want to check if username exists:
if "Jack" in logins:
print("Jack is a username")
Check if password is correct:
if logins[username] == inputed_password:
print("Password is correct.")
Note:
All of these names and passwords are made up. You can use any you want.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After I type in any username and password (doesn't matter whether it's correct or not), it keeps printing another part of the code.
The login part works fine but it doesn't show the correct output afterwards. It continuously shows:
"Incorrect login details entered
Have you made an account?
Yes or No"
This has stumped both my teacher and I. I have looked at different websites with examples of login/registration systems. I have also tried re-arranging the code differently.
This is the code:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("Usernames.txt","r")
found = False
for line in file:
user = line.split(",")
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while ans not in ("Yes", "No"):
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
elif ans == "No":
print("Would you like to make an account? ")
else:
ans = input("Please enter Yes or No ")
The expected result when the username and password is correct:
Username: Smartic
~~~~~
Welcome to the game, Smartic
The expected result when the username and password is incorrect:
Incorrect login details entered
Have you made an account?
Yes or No
The expected result when the user enters Yes:
Please sign in again
Please enter your correct username:
Please enter your correct password:
The expected result when the user enters No:
Would you like to make an account?
The expected result when the user enters something other than Yes or No:
Please enter Yes or No
No matter what username you enter, it won't satisfy every username in the file. Every time it doesn't, your error text will be printed. Reformat your code as is described in this question.
There is a new line at the end of each line in the file. You can remove newline by using strip() function.
if user[0] == username and user[1].strip() == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
Change your:
while ans not in ("Yes", "No"):
In:
while True:
Besides I can recommend to make a function.
Also as John Gordon mentioned use breaks, so your script will look like:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
user = {0:'e',1:'w'}
found = False
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while True:
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
break
elif ans == "No":
print("Would you like to make an account? ")
break
else:
ans = input("Please enter Yes or No ")
break
This code is at the start and when I run the code it doesn't do anything and nothing shows up, please help?
users = {}
status = ""
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()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
I expect the output to be a login system that then leads to a quiz but when I run it all I get is blank space
All you're doing is creating a couple of variables and declaring some functions.
Neither of those things will result in any output. If you want the functions to run, you'll actually need to call them from somewhere, such as by putting register() or login() (with no indentation) after the function definitions.
You defined the functions, but didn't call either, you should call one or both at the end of your script like :
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()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
login()
userlist = {"MMonroe": "SomeLikeItHot1962",
"NMandela": "Justice_27years",
"ALincoln": "Number_16"}
username = input("What is you username? (FLastname)")
if username in userlist:
passw = input("What is your password? :")
if passw in username:
passwnew = input("Enter password again:")
else:
newac = input("password is invalid, try again or would you like to create a new account(y/n)?")
if input == "y":
username = input("What is you username? (FLastname)")
passw = input("What is your password? :")
passwnew = input("Enter password again:")
else:
print("Try again later or create new account")
if passw != passwnew:
print("The password is invalid, try again")
else:
print("Welcome to the website")
Seems like you meant to check if the password for that user was incorrect. Don't use in for that
if passw != userlist[username]
Also, if input == "y" will never be true unless you overwrite the input() function with a string variable