I want to create a class based user registration portal and for that I wanted to add some usernames. But if they are already taken, then the code should prompt the
user to add another username and I tried to do so with this code.
a=0
User=['name123']
username=raw_input("Enter username : ")
while a==0:
for i in User:
if i==username:
a=0
break
else:
a=1
if a==0:
usernarme=raw_input("Username already taken.\nEnter another username :")
But it gets stuck in the loop and displays the following message repeatedly
even after entering a valid username. What I am doing wrong?
"Username already taken"
That will fix all your issues with loop.
User=['name123']
username=raw_input("Enter username : ")
while username in User:
username=raw_input("Username already taken.\nEnter another username :")
P.S. I'm strongly recommend you to read Dive Into Python and The Zen of Python
Here's a more pythonic version of your code, that's easier to understand and to fix:
users = ['name123']
username = raw_input("Enter username : ")
while username in users:
username = raw_input("Username already taken.\nEnter another username :")
Notes:
Always use lower case for variable names.
Use in instead of looping over users explicitly in the loop.
Avoid break in a while loop and rather change the value of
your loop condition.
Related
I need to know how can I make my program continue with the login ONLY if the entered username is valid, but if an incorrect username is entered it should stop, but the break function just doesn't work.
I am a beginner, and I am truly sorry about posting about something this simple, but I cant get it to work and I cant find a direct answer elsewhere.
Code:
if a == x:
print('entered username is valid')
else:
print('entered username is invalid')
break
I tried using {}, and it didn't quite work; it said something about just not working properly but the brackets don't work in any scenario.
while a!="":
if a!=x:
print("username invalid")
break
else:
print("username login valid")
b=str(input("enter password"))
if b==y:
print("logged in successfully")
break
you can work with something similar, break are only for loops , you should integrate it with while/for loop, for this example we entered in a loop that loos on while your "a" username input is not empty
break is for loops. If you want your program to stop, try replacing break by sys.exit().
Of course, you'll need to add at the beginning of your program:
import sys
because sys.exit() is a function of module sys.
So I have been tasked with creating a Login function using an intake from a pickle file, my only issue (that I have noticed) so far is that I can never get out of the loop.
for counter in range(len(Users)):
UserN = input("Username: ")
if UserN in Users[counter]:
PassW = input("Password: ")
if PassW in Users[counter]:
print("User Authenticated")
break
else:
attempt = 1
while attempt != 4:
print("Password Incorrect | Attempt", attempt)
PassW = input("Password: ")
if PassW in Users[1]:
print("User Authenticated")
MainMenu()
else:
attempt = attempt + 1
if attempt == 4:
print("\nToo many attempts, you are locked out")
exit()
else:
print("\nUser not found!\n")
If the user is authenticated, the count of the attempt will stop increasing, but the condition for the while-loop is stop is attempt == 4, so it will be stuck until the user has typed in the wrong password 4 times.
To fix it, either add a variable authenticated before the while-loop and initialize it as False, then set it to True once the user has successfully been authenticated.
attempt = 1
authenticated = False
while attempt != 4 and !authenticated:
...
if PassW in Users[1]:
...
authenticated = True
Or if you don't want a new variable, simply break by
if PassW in Users[1]:
...
break
to break the loop
If you the password is found, you call another function but you never exit from the loop. You should add a break statement.
You can add a break statement under
MainMenu()
break;
The logic in your code seems quite wonky.
This code assumes that the username is the first appearing in Users; if the second user logs in, they need to enter their name twice, the third user 3 times, and so on. If you mistype your name on your "turn", you won't be able to log in at all.
I would suggest the following structure:
Turn your variable "Users" into a dictionary, mapping user name to password.
Ask the user name.
If the user name does not appear, either stop or loop (you might want to prompt to ask whether they want to try again or not, or just let them press ctrl-D to stop (and catch the ensuing EOFError or KeyboardInterrupt (which happens if they press ctrl-C instead).
Some other issues, that are not as crucial for this question but good guidelines:
Use proper style conventions. Variable names should not start with upper case characters. Same for goes for functions. It should be users, passw, main_menu().
You really should not store passwords in a pickle file; that is obfuscation rather than security. Have a look at https://www.geeksforgeeks.org/getpass-and-getuser-in-python-password-without-echo/ for better practices.
When you say the user is locked out, nothing actually happens. They are not really locked out; they could just try again. That means you can just create a bit that brute-forces password guesses
Let them enter the password, with a maximum number of guesses.
A good rule is to test for attempt > 3 instead of attempt == 4. This does not make a difference here, but in larger functions, it's often good practice to make the test a bit "wider".
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
So, noob here, now that's out of the way let's get to the problem shall we?
(First post, ever)
So, my code (below) is quite inconsistent. I have just begun, about two days ago, and I'm dying to become better and love all kinds of critique, so unload all you've got.
When the user enters "login" to login he gets prompted to enter the username (a separate function creating a global variable for the password function to use as the welcoming name.) and is immediately redirected to the password check. Here there are two outcomes: 1. The user types in the correct password, the user will be "let in:" "Welcome " + username + "." 2. The user types in the wrong password/types anything that isn't the password: the user is sent back to the username check. But what happens for me is that the Python instead jumps back to the intro code and exits the program with: "Invalid input." And it seems as if the program goes to the password function, does its thing and immediately reverts to the former function.
Tl:Dr: Functions don't loop as they should, instead return to the previous function, thus ignoring the action I wrote.
Excuse me for the wall of text, and please, please please for the love of god or anything, don't hit me with a wall of code and "Fixed!" I'm very new and barely understand anything outside this patch of code which I myself wrote with my new gained experience. Otherwise it will end up with a [ctrl + c --> ctrl + v] situation and I really, really want to learn, not copy. So if you think you have what it takes, please do your best, everything is appreciated :)
Ps: Tips & Tricks are valuable for me!
PPs: If you want more code, just say it and I'll do my best.
Changes in the login screen:
choice = input
if input blah blah:
"function"
creating a whole function for it
moving the commands around
messing with other codes
# Password check.
def password_check():
print("Please enter your password")
print("")
password = input("")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")
Your if statement checking password was in the global area and not inside your function.
# Password check.
def password_check():
password = input("Please enter your password\n\n ")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")
Pretty new to Python, trying to create a simple login system here (has to be done this way). I've already defined a user() function which asks for the username and checks its validity. This function starts by calling the user function. Here is the main part:
user()
if user in userlist:
while True:
pass = raw_input("Enter password, or X to retry: ")
if pass == 'X':
break
if userlist[user] == pass:
break
else:
print "Invalid password."
I want the function to loop back to asking for username input if X is entered. The rest of it works fine but as it stands, entering X just ends the function and doesn't loop it back to the start. Is this just not possible or can I rewrite it to work? I assume I'd need to include user() into the loop but I've encountered various errors while trying.
You intentionally say to exit the loop if the user enters X by using the break statement. That's why the loop is exiting. Instead of break use continue.
if password == 'X':
continue
This will start the loop over again at the top.
As another user notes, you can't use pass as a variable name. The code you posted clearly isn't the code you're actually running. Anyway, I've assumed that you really used the name password.
Don't use pass as a variable name because it clobbers the builtin pass. What you want is
if passwd == 'X':
continue #restart at top of loop
You'll have to do:
if password == 'X':
continue #restarts loop at while
checkSql = 'SELECT userid FROM bs_members WHERE userid = :checkUser'
doesUserExist = False
while True:
doesUserExist = False
newUser.userID = ga.getInput('Enter userID: ', "\w+$")
checkUserID = ds.execute(checkSql,checkUser=newUser.userID)
for row in ds:
if row == checkUserID:
doesUserExist = True
print 'That user name is already in use. Please enter a new username.'
break
if doesUserExist == False:
break
else:
continue
I am using the cx_Oracle module with Python 2.7. I am trying to prompt the user to enter a userID. The program will then check if the userID already exists and if it does prompt the user for a different userID. The execute method is a helper method that uses the execute method from cx_Oracle to interact with the Oracle database. The getInput method prompts the user for input that is then checked against the regular expression.
I know I have this wrong but I believe the while loop starts the first action that is taken is the user is prompted for a userID. Then the userID is checked against the database. The for loop starts and checks if the row returned by ds.execute() is the same as the userID provided by the user. If it is the user is told to use another user name and the break exits the for loop. The if statement then checks if a user exists and if it doesn't it breaks the while loop. If not then the while loop iterates so the user is prompted to enter a non-existent userID.
What happens is the user is prompted for the userID then none of the checking ever appears to happen to the user and the program moves on to the next piece of code. What am I missing here? I have included a link to the docs for execute(). The execute method in the above code is part of the following helper method:
def execute(self, statement, **parameters):
if parameters is None:
self._curs.execute(statement)
else:
self._curs.execute(statement,parameters)
If I need to provide more information let me know.
edit: I forgot the line doesUserExist = False immediately after the beginning of the while loop so I added that.
Your custom execute method doesn't return anything meaning that checkUserID in your code will be None.
Furthermore, what you're interested in is if there's at least one row returned by the query. If there are none then the userID should be available.
The docs say that calling .fetchone() returns None if no more rows are available. You can use that.
checkSql = 'SELECT userid FROM bs_members WHERE userid = :checkUser'
while True:
newUser.userID = ga.getInput('Enter userID: ', "\w+$")
ds.execute(checkSql,checkUser=newUser.userID)
if ds.fetchone() is None:
# This userID is available.
break
else:
print 'That user name is already in use. Please enter a new username.'
I'm assuming here that ds is an instance of Cursor, or subclass thereof.
At least you should have line doesUserExist = False at the beginning of the while loop. Otherwise, if user enters an existing ID once then it will keep looping forever.