I'm trying to make a small program which can tell whether or not the correct password has been entered and keep asking for the correct password until it is entered. The correct password is 'Secret'.
I get as far as creating my while loop. It will ask for the password and ask to enter it again, but it will do this regardless of whether you enter the correct password first time round or not. Where am I going wrong? And how can I get it to break if the correct password is entered first time and how do I keep it asking for the password until it is entered correctly?
This is my code so far:
password = raw_input('What is the password? ')
correctPassword = 'Secret'
tryAgain = raw_input ('Enter password again ')
password
while password == False:
print 'Enter password again '
if password == correctPassword:
print 'You are in!'
break
Try the below code: -
password= raw_input('What is the password? ')
correctPassword= 'Secret'
while password != correctPassword:
password = raw_input ('Enter password again ')
print "Success"
This will execute the while loop until the password input in the while loop is not equal to the correct password.
Here is the right code.
correctPassword= 'Secret'
while True:
password= raw_input('What is the password? ')
if password == correctPassword:
print 'You are in!'
break
print 'Enter password again '
Here is my code
password = 'password'
Get_password = input("Enter the password: ")
while Get_password != password:
print("the password you entered is not correct, enter the correct password")
break
print("You are logged in!")
Related
How would I put "if" or "else" in code like this?
user = input('Login: Username\n')
time.sleep(1)
password = input('Login: Password\n')
print('Welcome, %s.' % user)
I think this is what you want to do. But this is not a secure way of doing password requests.
user = input('Login: Username\n')
password = input('Login: Password\n')
users = {"You" : "1234", "Me" : "abcd"}
if user in users.keys():
if users[user] == password:
print("Welcome, {u}".format(u=user))
else:
print("Wrong password")
else:
print("This user does not exist")
Here is a simple version on how this should work but is not secure at all, but functions (almost) the same way as you requested (came up with this under 5 mins)
user = input('Login Username: ')
password = input('Login Password: ')
if user == ("Your username here"):
if password == ("Your password here"):
print("Welcome ", user)
Also you do not need "time.sleep()" as it only slows down your code
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 first want to thank anyone and everyone in advance for taking the time to help a scrub like me and appreciate your time in giving me a helping hand. So I am attempting to make a simple user creation script. Asking the user for their first and last name, concatenated the user's first letter of their first name with their last and concatenating it with a random number to create their user name. I then will prompt the user to create a password and have the password be a minimum of 6 characters long. After that, I ask the user to verify their password. I've been going crazy because when the program reaches the password verification step, it doesn't check for the 6 characters or verify that the passwords are the same and continues to the rest of the program.
This is a snippet of the password part:
# Ask the user for a password that's at least 6 characters long
while True:
password = input("Enter a password for this account: ")
# Verify that the user's input is 6 characters long
if len(password) < 6:
print("Your password must be at least 6 characters long! ")
# Has the user verify the password
password = input("Please verify your password by typing it in again: ")
if password == password:
print("Thank you for confirming your password")
else:
print("Nope your password did not match")
And after all of that, I am having the "user" login with the new information that was generated. Using the username generated in the first part and using the password they input in the second and checking. The same thing, it skips the check and continues with the program. I am going insane because I've spent a couple of hours just learning some basics as I am a beginner with python.
Here is the full code:
def main():
print("You do the typin, I will take care of the rest!")
#User will be prompted to input their first and last name
firstname = input("Please give me your first name. ")
lastname = input("Thank you, now please give me your last name. ")
# The first and last name will be concatenated and the first letter of the
# users name will be attatched to their last name.
username = firstname[0] + lastname[:7]
# Now to generate the random number from 100-999 to attach to the new
# username
import random
from random import randint
print("Welcome", username + str(random.randint(100,999)))
import re
def sub():
# Ask the user for a password that's at least 6 charcaters long
while True:
password = input("Enter a password for this account: ")
# Verify that the users input is 6 charcters long
if len(password) < 6:
print("Your password must be at least 6 charcaters long! ")
# Has the user verify the password
password = input("Please verify your password by typing it in again: ")
if password == password:
print("Thank you for confirming your password")
else:
print("Nope your password did not match")
# Now the user must login using the generated username from above
username = input("Enter your generated username! ")
if username == username:
print("Correct!")
else:
print("I have never seen you before!")
password = input("Now enter your accounts password: ")
if password == password:
print("You are now logged in!")
else:
print("FAIL")
break
main()
sub()
So, there are many errors in your code. The first one is, there's nothing that stops the program from progressing if the password is less than 6 characters. Second, password == password will ALWAYS return true, because you're checking a var against itself. I re-wrote a bit of your code to try to help clarify your problem. I hope this helps! I also split the code into a few functions + added getpass (https://docs.python.org/3/library/getpass.html)
from getpass import getpass # You can use this module to hide the password the user inputs
from random import randint
def generate_username():
# Basic username generation, same thing you did
print("You do the typin, I will take care of the rest!")
firstname = input("Please give me your first name. ")
lastname = input("Thank you, now please give me your last name. ")
username = firstname[0] + lastname[:7] + str(randint(1, 99))
# You can't concatenate strings and ints, so I convert the number to a string first
print(f"Your username is: {username}") # f-strings (https://realpython.com/python-f-strings/)
return username
def generate_password():
while True:
password = getpass("Enter a password for this account: ")
confirm_password = getpass("Enter your password again: ") # Ask the user to enter the password a second time to confirm
if password != confirm_password: # Check if the user entered the same password
print("Passwords dont match!")
elif len(password) < 6: # Check the length
print("Your password must be at least 6 charcaters long! ")
else: # If everythings all good
print("Password is valid!")
return password # Break the loop and return password value
def login(username, password):
# Used to login a user
while True:
entered_username = input("Enter your username: ")
entered_password = getpass("Enter your password: ")
if username == entered_username and password == entered_password:
# Confirm if username and password are correct, then exit the loop (or do something else)
print("Login successful!")
break
else:
print("Login failed, please confirm your username and password")
username = generate_username()
password = generate_password()
login(username, password)
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.
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()