I'm trying to do a simple password check with limited retries.
If user keys in wrong password, program prompts to try again (3 retries).
After 3 failed retries, program prompts user has reached maximum retries.
If User keys in correct password, program will "grant access".
import sys
print (sys.version)
pssw = ''
attempt = 0
print('Please key in your password.')
while (pssw != "remember") and (attempt < 3):
pssw = input()
attempt = attempt + 1
print ('No that is not correct. Try again.')
if attempt == 3:
print ('Sorry you have reached maximum number of attempts')
break
if (pssw == "remember"):
print('Access Granted!')
Problem #1
Expectation: After keying in the correct password "Remember", program should print output "Access Granted"
But program output:
3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
Please key in your password.
remember
No that is not correct. Try again.
Access Granted!
Problem #2
Expectation: After keying in the correct password "Remember" on the last try, program should print output "Access Granted"
But program output:
Please key in your password.
test
No that is not correct. Try again.
test
No that is not correct. Try again.
remember
No that is not correct. Try again.
Sorry you have reached maximum number of attempts
What am I doing wrong?
I will just explain your errors because someone posted another code approach.
I think it's important that you understand your erros and do not just copy another code.
First, the line break is incorrect because a break cant be outside a loop, use sys.exit() instead.
Problem #1:
If you enter the right password your program will exit the loop and execute the next statements:
print ('No that is not correct. Try again.')
if attempt == 3:
print ('Sorry you have reached maximum number of attempts')
break
if (pssw == "remember"):
print('Access Granted!')
So it will print "No that is not correct. Try again.".
Check if attempt is equal to 3. It isn't because you entered the right password at the first attempt.
Check if password is equal to "remember". It is, so program will print "Access granted".
Problem #2:
Your second output is incoherent with the code you posted.
Normal output for the code you posted is:
Please key in your password.
test
test
remember
No that is not correct. Try again.
Sorry you have reached maximum number of attempts
This is the normal output for the code you posted, but it's wrong anyway.
It's because if tou type an incorrect password, the loop will just continue and thus ask again for your password without printing anything.
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".
Please don't judge me.. I've only been working with Python for a month now.
While laying in my bed I thought of making this and created it in a few minutes but I made to many else and if statements and my code just looks so messy, I kept adding things that weren't needed..(For fun :D)
Anyways, here is my code.. If you could tell me how to use the "elif" statements properly that'd be awesome.(I'm still learning python)
Question: I've tried using an elif statement multiple times and I keep getting an error. How do I fix this?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")
We can't debug code you haven't posted, and (as is to be expected - you are on a learning exercise here, and there's a lot to think about) your program structure isn't very helpful. For example, when the user enters non-matching passwords you tell them about it, but nevertheless continue to ask them for their username. Don't worry about this, you will soon learn how to fix it.
Since you ask about the elif, it is basically a syntax abbreviation for else if that avoids going to multiple indentation levels. Suppose you wanted a value of '1' or '2' to take different actions, and to declare other values invalid. You could write
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Note that the different actions are at different indentation levels. The more cases you have to consider, the more levels of indentation you have to introduce. So it's generally felt to be more readable to write
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Now all the actions and decisions are at the same indentation levels. That's pretty much all there is to it. If you leave the else case off then you won't take any actions at all, so it's normally used to specify the default action, in this case raising an exception.
PS: If you want to be sure the user has entered two matching passwords before you proceed, look at the while loop, which allows you to repeat a set of actions until some condition (in this case the passwords being equal) is true.
Here is an example if if/elif/else statement in python3:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
You can find more information here : https://docs.python.org/3/tutorial/controlflow.html
EDIT:
As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)
So using Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
Though what is this error you're getting, we can't really help you without it.
Beginner here. :)
So I want to achieve is this:
User enters a number. It spits out the ^3 of the number. If user enters a letter instead, it prints out a error message.
Code #1 works great:
def thirdpower():
try:
number = int(raw_input("Enter a number : "))
n=number**3
print "%d to the 3rd power is %d" % (number,n)
except ValueError:
print "You must enter an integer, please try again."
thirdpower()
thirdpower()
But I want to try doing the same thing with a while statement since I want to practice with it. I know its a bit more verbose this way, but I think it's good practice nonetheless.
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
number=raw_input("Please Enter an integer")
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
My question is this. If I remove the number=raw_input("Please Enter an integer") under the while statement and replace it with a break, the code doesn't work.
Here is what I mean:
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
break #This break here ruins everything :(
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
Can anyone explain why?
The break exits out of the while loop, at which point number is still whatever letter was entered so you get an error trying to make it an int.
A break statement jumps out of a loop.
In this case, if the user types in a letter, the loop runs the print statement, then immediately reaches the break and terminates instead of looping over and over. (break is more useful when you put it inside an if statement that the program doesn't always reach.)
But using break doesn't stop the rest of your program from running, so Python still tries to run line 6. Since the number variable contains a letter, the program crashes when it tries to convert it to a number.
You were probably trying to end the program if the user typed in a letter. In that case, you could use the built-in sys module to do something like this:
import sys
number=raw_input("Please Enter an integer")
if number.isalpha():
print "You have entered letter. Please try again"
sys.exit()
#...
The function below calls for the input command and check if str.isalnum().
def enterPass(str):
x = raw_input("enter password Alpha or Alphanumeric! 'No_Space' :")
if x.isalnum():
print "saved"
else:
print "try again"
return;
Followed from the above is the below function, which exists when the function enterPass has been called 3 times.
_try = 1
while (_try <= 3):
enterPass("password")
_try += 1
My intention was that upon entering password it should verify if it is Alpha-Numerics or not. If so, it should prompt "Saved" and quit, if not then it should ask for the password again, and if the user cannot get the password right 3 times, the program shoudl quit.
The problem I am facing is that I am unable to quit this program once it had successfully accepted the isalnum() with "Saved" prompt. It is going again in the loop asking to enter my password again. Please suggest how I can make this function work as intended, and possibly more efficienty.
The above program is just for academic purpose and has no useful application at present.
A function is probably not needed in this case, as you can then use break:
tries = 0
while tries < 3:
x = raw_input("Enter password Alpha or Alphanumeric! No spaces! ")
if x.isalnum():
print "Saved"
break
print "Try again"
tries += 1
Here's a test:
Enter password Alpha or Alphanumeric! No spaces! Hi!##
Try again
Enter password Alpha or Alphanumeric! No spaces! !##!##
Try again
Enter password Alpha or Alphanumeric! No spaces! ####
Try again
>>>
Enter password Alpha or Alphanumeric! No spaces! No!
Try again
Enter password Alpha or Alphanumeric! No spaces! Okay
Saved
>>>
You could import sys and do sys.exit(0)
import sys
if x.isalnum():
print "saved"
sys.exit(0)
Now sys.exit will give you a bunch of errors when it's exiting the program when running in an IDLE, ignore those because in the actual final program they will not appear.
But that is if you want to terminate the whole program. If you simply want to break out of the loop and continue the program with something else you can do
if x.isalnum():
print "saved"
break
Break must also be in a loop for it to work.