Python 2.7 for loop and not printing the right time - python

Okay so i am writing a simple login system, here is the code
import time
for counter in range(5):
username=str(raw_input("Please enter your username"))
password=str(raw_input("Please enter your password"))
if username =="bros10":
print "",username,"entered"
time.sleep(4)
print "You got the username right"
if password =="brosbros10":
print "You got the password right"
print "Welcome to the system"
break
else:
print "Try again"
And what happens when i run it is that it will print this bit print "",username,"entered" after i have entered the password
Any help appreciated

Move this:
print "",username,"entered"
To before this:
password=str(raw_input("Please enter your password"))
Now your program will ask for a username, repeat the username that is entered (and tell the user they got it right if they entered bros10), then ask for a password, then sleep 4 seconds.
Alternatively, you can place the password= line right before this one
if password =="brosbros10":
if you want it to ask for the password after waiting 4 seconds and repeating the user input.

If I understand you correct you want to print "",username,"entered" before entering a password. Then it should look like:
import time
for counter in range(5):
username=str(raw_input("Please enter your username"))
print "",username,"entered"
if username == "bros10":
print "You got the username right"
password=str(raw_input("Please enter your password"))
time.sleep(4)
if password =="brosbros10":
print "You got the password right"
print "Welcome to the system"
break
print "Try again"

Related

How do I store multiple strings as one variable

I have the write a if and else statement for every supposed user using my code in order to make sure they are who they are. I am wondering if there is a more efficient way to do that. What I want the code to look like is line 2 to 7 however currently I have to make it look like line 9 - 14 instead. Is there any way I can make line 2 to 7 work?
I've already tried to separate each user with a separate if and else statement which checks for whether the user exists already and if they get the password that is assigned to that user correct. I've also tried to already use a list function to store multiple different users as one variable so that if the program detects any of those users it moves them onto the next step however once I do that the program refuses to recognize any of the elements of the list as individuals.
For example in line 2 of the code neither of the users are recognized. The user blake is only recognized if I separate it in its own if else block.
user_name = input ("Hello, user please enter your username!")
if user_name == ["Jake", "Bake"]:
Password = input("Please enter your password %s" %user_name)
if Password == ["hello", "notem"]:
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
else:
if user_name == ("Bake"):
Password = input("Please enter your password %s" %user_name)
if Password == ("hell"):
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
Out of line 2 to 7 I expect that I can enter either Jake or even Blake to get the password question. Then once I put the corresponding, and only the corresponding, password then I should be getting a welcome back (which ever username I chose to go with). In reality the program quits on me as soon as I put in any of the usernames because it seems that the program doesn't know how to proceed from the username prompt.
if user_name == ["Jake", "Bake"]:
checks whether user_name equals the list ["Jake", "Bake"].
If you want test check whether the name is in the list, use the keyword in:
if user_name in ["Jake", "Bake"]:
Your problem is that the program checks to see if the username is the list ["Jake", "Bake"] and the password is the list ["hello", "notem"].
The correct code is:
user_name = input ("Hello, user please enter your username!")
if user_name in ["Jake", "Bake"]:
Password = input("Please enter your password %s" %user_name)
if Password in ["hello", "notem"]:
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
else:
if user_name == ("Bake"):
Password = input("Please enter your password %s" %user_name)
if Password == ("hell"):
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")
Edit: you forgot to treat the case in which the user name is neither Jake nor Bake.
As pointed out by #DSC earlier:
What you've checked in your if statement is whether or not the input given by the user is a list in itself.
Instead what you should be checking is whether the input given by the user is an object inside the list.
Also, note using dictionary to hold { 'Username' : 'Password' } key:values will be helpful to match the username to the exact user's password, in case of multiple users.
users = {'Jake':'hello','Bake':'notem'}
user_name = input ("Hello, Please enter your username: ")
if user_name in users: #Checks whether user exists
Password = input("Please enter your password %s" %user_name)
if Password == users[user_name]: #Check for that particular user's password.
print("Welcome back %s" %user_name)
else:
print("You are an imposter! Begone!!")
else:
print('Sorry, That username doesn't exist.')
Not the safest way to go about, as it tells the potential attackers what exactly they've gotten wrong (The username/Password), But should do your work.
Also check this, should get you a few more steps ahead.
Supposing that you want to check for the username and password corresponding to that username, python provides structure called dictionary. May this will be helpful to you.
userPass = {"Jake": "Hello", "Bake": 'notem'} #dictonary named userPass, "username": "Password"
user_name = input ("Hello, user please enter your username!")
Password = input("Please enter your password %s" %user_name)
if userPass[user_name] == Password: #userPass[user_name] will return password defined in dictonary
print ("Welcome back %s" %user_name)
else:
print ("You are an imposter! Begone!!")

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