How do I deal with unlimited loop problems? - python

so i have this code
pa=""
newpa=""
use=''
use=input('enter username:')
pa=input('enter password')
while True:
if len(pa)==12:
newpa=input('re-enter password:')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
if newpa==pa:
print('you have successfully created a new account!')
whenever I insert a pa that's incorrect the else print keeps looping. How do I make it so whenever I enter a pa that doesn't meet the if to loop back to newpa
if this help this is my algorithm alogrythm of what I am trying to go for

First thing to do would be the put the input statement inside the while loop. At the moment your code loops back to the top of the while loop without giving the user a chance to re-enter their password.
You'll also want to move the check for the re-entry part so that it only executes if the first password was valid. And let the user know if their passwords didn't match.
Finally, you'll want to break the loop when a valid password is entered and verified. Use break for this.
The final code would look like this:
pa=""
newpa=""
use=''
use=input('enter username:')
while True:
pa=input('enter password')
if len(pa)==12:
newpa=input('re-enter password:')
if newpa==pa:
print('you have successfully created a new account!')
break
else:
print('the passwords did not match!')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
Hope that helps and makes sense!

Your loop will run continuously until you add break statement.
You can try something like below,
pa=""
newpa=""
use=''
use=input('enter username:')
while True:
pa=input('enter password')
if len(pa)==12:
newpa=input('re-enter password:')
if newpa==pa:
print('you have successfully created a new account!')
break
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')

When you enter in the last if you want to exit from loop. So, add break after print.
if newpa==pa:
print('you have successfully created a new account!')
break

Use a while True loop and break from that loop if the password meets the requirements. Then you can enter the password a second time and compare if both inputs match.
username = input('enter username:')
while True:
password = input('enter password')
if len(password) == 12 and password.isdigit():
break
print('the password used did not meet our system requirements, please enter a 12 digit password')
password_check = input('re-enter password:')
if password == password_check:
print('you have successfully created a new account!')
You might want to wrap that in an additional loop if the passwords don't match.
If you use functions you can reduce the complexity of the main part.
def enter_password(message):
while True:
password = input(message)
if len(password) == 12 and password.isdigit():
break
print('the password used did not meet our system requirements, please enter a 12 digit password')
return password
def main():
username = input('enter username:')
while True:
password = enter_password('enter password')
password_match = enter_password('re-enter password')
if password == password_match:
break
print("The passwords don't match.")
print('you have successfully created a new account!')
if __name__ == '__main__':
main()

Please use break to break the statement and continue to continue the loop statement according to your requirement. I hope the following code meets your requirement. Thanks and let me know if there's anything I can help with.
user=input('enter username:')
while True:
pa=input('enter password:')
if len(pa)==12:
newpa=input('re-enter password:')
while newpa!=pa:
newpa=input('re-enter password:')
else:
print('the password used did not meet our system requirements, please enter a 12 digit password')
continue;
if (newpa==pa):
print('you have successfully created a new account!')
break;

Related

Counter won't update

beginner programmer with python here. I'm wondering why my "attempt" counter only updates once despite the loop continuing.
def login():
attempt = 3
username = input("Enter your username:\n> ")
while True:
if username in userNamePassword:
password = input("Enter your password:\n> ")
if userNamePassword[username] == password:
print("Logged in")
return True
elif userNamePassword[username] != password:
attempt -=1
print("Sorry, the password is invalid. You have", attempt,"attempts remaining.")
login()
if attempt == 0:
print("Sorry, you have exhausted your password attempts. Please restart the process.")
exit()
It only ever prints 1 as the attempt remaining however continues the loop asking for the user and pass once more. It's possibly a small, overlooked issue but I'm scratching my head here. Thanks
Remove that login() call. When you call the function, the attemps will reset to 3. If you don't call it, you will stay in loop and the attemps will decrement. I recommend you, instead of exit() to use break

How do I Avoiding Looping back to lines in code?

I am self-teaching myself python and have run into a problem that I can not seem to find a way around.
I have created a piece of code that compares an entered password to one stored in a database.
My code should have two possibilities.
1) If the password is correct.
The user is prompted to enter a new password and then the prompt to enter the password must appear again (This time accepting the new password).
2)If the password is incorrect the user will be prompted to enter the password until the correct password is entered.
In VBS I used to be able to use the GOTO command.
I am not sure if this is available in Python and if it is I would like to avoid using it as it creates a very illogical hard to follow the program.
password = "#123"
entry = input("Please Input The Password:")
if (password == entry):
entry = input("Password correct you may enter a new password.")
else:
entry = input("Password Incorrect, Try again.")
There are various ways you could complete this. Here is a simple way you could achieve it using while loop and break statement.
password = "#123"
while(True):
entry = raw_input("Please Input The Password: ")
if (password == entry):
print("Password correct you may enter a new password.")
break
else:
print("Password Incorrect, Try again.")
Hope it helped.
while password != entry: # Executes until (password == entry), and does not execute if it is met, even for the first time.
print('Sorry, wrong password.')
entry = input('Enter password >') # or other source of data
print('Correct!')
Edit: additional ways you can do this:
while True: # forever loop, but
entry = input('Enter password >') # or other source of data
if password == entry:
print('Correct!') # you can also put this outside of the loop
break # exit the loop no matter what
# do not put code after the break statement, it will not run!
print('Sorry, wrong password') # will execute only if password != entry, break ignores the rest of the code in the loop
Easiest to make a function with a while statement.
password = "#123"
def login():
while True:
answer = input("Please Input The Password:")
if answer == password:
print("Password correct you may enter a new password.")
else:
print("Password Incorrect, Try again.")
break
login()

Python - Beginner Level - User input and while Loop combination

I have did a little research around "Google", "YouTube", "Facebook" and "Stack Overflow" and I haven't found what I was looking for. So, I need your guidance. :)
I want program to ask user input "PASSWORD" and every time user inputs wrong password the program asks password again, and again, and again until user
types the correct password. Let's say that the password is as simple as "abc123".
So, I start the program and it asks to input: "PASSWORD: ". If user types "abc123" then program prints "GOOD PASSWORD". If user types anything what is not "abc123" then program prints "BAD PASSWORD". As simple as that.. for now.
My best attempt:
#SECTION1_ASKING
passwordInput=input('PASSWORD: ')
password='abc123'
while password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
#SECTION2_RE-ASKING
while False:
while password == paswordInput:
print('GOOD PASSWORD')
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
but I either make password asked once or twice or I stuck in Infinite while Loop.
Try this:
passwordInput=raw_input('PASSWORD: ')
password='abc123'
while True:
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=raw_input('PASSWORD: ')
You can do as below in few lines.
password='abc123'
while(True):
passwordInput=input('PASSWORD: ')
if(passwordInput==password):
print("Good password")
break
else:
print("Bad password")
Here is my solution:
password = 'abc123'
while True:
passwordInput = input('PASSWORD: ')
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
How does that differ from yours? For a start you can see that I only have one call to input(), that's generally a good idea because then you only need to check the password in one place. Notice that I use if instead of while for the test.
In your second example you have while False:. Can this ever be True? No, so it won't get executed.
Notice as well that I use more whitespace. That does not slow the program down, it makes it easier to read. See also PEP008
Now you have it working, just for fun, consider an improvement. Normally you don't want the password to be visible when it is typed, but there's a module for that: getpass - it's part of the standard library so you don't need to download anything.
Add import getpass to the top of your script. Instead of input use getpass.getpass, in the same place in the program, with the same parameters. Now it won't echo the password entered by the user.
getpass is the module name, getpass is also a function name, so getpass.getpass('PASSWORD: ') means execute the getpass() function in the getpass module. We use lots of modules in Python, so its worth getting used to using them. You can find the documentation here, note there is also a getpass.getuser() to play with.

Making a login forum in Python 3 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Checker = 'Incorrect'
name = input('Please Enter Your Name: ')
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
if Checker == 'Incorrect':
exit()
import time
time.sleep(5)
print('Password is Correct')
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
import time
time.sleep(1)
print ("Closing Python...")
import time
time.sleep(5)
input('Press Enter to continue...')
exit()
I need help , the correct password is badger123 but even if I enter the correct password it will print 'password is correct' and then exit but I want it to ignore exit and continue. When the wrong password is entered then the program will print incorrect and will exit. The programs reacts correctly when the incorrect password is entered but not when the correct password is entered. I NEED HELP!
The value of Checker never actually changes, so
if Checker == 'Incorrect':
exit()
always evaluates to True, which means exit() is always called.
One solution is to do the checking in the if statement
import time
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Password is Correct...')
else:
print('Password Incorrect')
exit()
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
time.sleep(1)
print ("Closing Python...")
input('Press Enter to continue...')
First you only need to import a module once (by convention at the top of your file), and not each time you want to use a function.
The problem you describe is impossible with the code you show
Checker = 'Incorrect'
if Checker == 'Incorrect':
exit()
Since you assign 'Incorrect' to Checker and never changes it after that, the rest of your code is not executed, and your program will never print 'password is correct', it will however print 'Checking Password...' when the correct password is entered and then exit because Checker is always the same, it's like doing if 1 == 1:exit()
Why it isn't working
You set value checker to "incorrect"
When the password is found to be correct, nothing is done about it. Nothing notifies the program in any way that the correct password has been entered. You can see in program that all the program does to acknowledge that the password is correct is simply say that it is "checking" and nothing else. 3 lines later the program will find that checker is still "incorrect" because the program, seeing that the password is correct does nothing to change checker so line 9 is inevitably going to happen.
Fix:
Put line 10 with the else statement and remove line 9. So your code will look something like.
password = input('Please enter your password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
exit()
I can suggest an improvement.
password = input('Please enter your password: ')
if not password == 'badger123':
print(Checker)
exit()
print('Checking Password...')
I think this would be the ANSWER to my question! , All I did is I changed the value of Checker. But now when the person gets the password wrong I want the program to automatically Restart . How do I do that?
Checker = 'Incorrect'
name = input('Please Enter Your Name: ')
password = input('Please Enter Your Password: ')
if password == 'badger123':
print('Checking Password...')
else:
print(Checker)
Checker = exit()
if Checker == 'Incorrect':
input(Checker)
import time
time.sleep(5)
print('Password is Correct')
time.sleep(3)
input('Press Enter to Continue...')
print ('Hello' , name)
import time
time.sleep(1)
print ("Closing Python...")
import time
time.sleep(5)
input('Press Enter to continue...')
exit()

What's going on with my if-else statement? (Python 3.3)

I'm writing conditional statements for a billing program project. It's a bit advanced for a beginner I know but I welcome the challenge. Anyways, I plan on starting the program with asking for username and password. So this is my first coding for the program.
print ("Hello and welcome to Billing Pro, please enter your username and password to access the database.")
username = input ("Enter username:")
if username == "cking" or "doneal" or "mcook":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
password = input ("Enter password:")
if password == "rammstein1" or "theory1" or "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")
Now at first when I ran this code if I had typed in anything other than the three choices for username Python printed out the 'invalid username' line. For some reason now, it's printing out 'valid username' and then going ahead with the password prompt. Also if I input anything other than the choices for passwords it will always read out the 'valid password' prompt.
Also how do I loop the username prompt when the user inputs something other than the three choices? Should I be using a while statement instead of if-else or can a while statement be placed at the end of the if-else statement to trigger the prompting again?
Oh and I know you can't tell because my crappy formatting in the question, but I did use proper indentation on the script itself.
The problem with your boolean expressions themselves is that they're always True.
if a == 'b' or 'c' is like if (True|False) or 'c', and since 'c' is truthy, it's True regardless of the first expression (a == 'b').
You either want a == 'b' and a == 'c'… or the more succinct a in {'b', 'c'…}, which checks if a is a member of the set.
If you want to loop, use a loop :)
while username not in {"cking", "doneal", "mcook"}:
print ("Invalid username. Please try again.")
username = input ("Enter username:")
print ("Valid username.")
You need to compare your name with all names. Problem lies here:
if username == "cking" or "doneal" or "mcook":
Python evaluates first one to either true or false and then doing or with something, that evaluates to True in this context and at the end your comparison looks like this:
if username == "cking" or True or True:
which ends up being True. As suggested, you should use:
if username == "cking" or username == "doneal":
or simply do:
if username in ("cking", "doneal"):
The same applies to password.
I think this code can help you
from sys import argv
username=raw_input("Enter user name")
password=raw_input("Enter password")
if(username=="VARUN" or "Varun" or "varun"):
print "\n\tvalid Username "
else:
print "\n\tUsername already existes"
if (password=="#ppu1131986"):
print "\n\tPasssowrd matched"
else:
print "\n\tWeak Password"
~
print ("Hello, welcome to Facebook, please enter your username and password to access.")
username = input ("Enter username:")
if username == "cking":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
username = input ("Enter username:")
if username == "cking":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")
password = input ("Enter password:")
if password == "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")
password = input ("Enter password:")
if password == "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")

Categories

Resources