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)
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
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")
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'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!")