Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have an assignment where I have to ask the user for a 4 digit pin. The correct pin is 1234. I have to give the user 3 times before they're locked out. I also have to add a break statement. This is the example of the output:
Please enter your pin code: 1112
Incorrect. Please enter again: 1112
Incorrect. Please enter again: 1234
Correct.
My code:
def verify_pin(pin)
if pin == "1234"
return True
else:
return False
tries = 3
while counter < 3:
pin = input("please enter your pin code")
if verify_pin(pin)
print("Correct")
break
elif
print("Incorrect.Please enter again: ")
tries +=1
I received an invalid syntax. I don't know what I am doing at all but I really want to understand and learn. Please help.
You are sort of close, but you have some issues with the code (mainly indentation issues, as mentioned in comments). Something like this should work though:
desired_pin = '1234'
max_tries = 3
def verify_pin(the_pin):
return the_pin == desired_pin
def main():
tries = 0
while tries < max_tries:
pin = input('please enter your pin code: ')
if verify_pin(pin):
print('Correct')
break
else:
print('Incorrect. Please enter again: ')
tries += 1
else: # Else will run when no `break` statement is run in while loop.
print("I am LOCKIN' you out now!")
if __name__ == '__main__':
main()
Sample interaction:
please enter your pin code: 111
Incorrect. Please enter again:
please enter your pin code: 222
Incorrect. Please enter again:
please enter your pin code: 123
Incorrect. Please enter again:
I am LOCKIN' you out now!
You have made some indentation and syntax errors. I have made some changes, please compare this with your code and you can understand the difference
def verify_pin(pin):
if pin == "1234":
return True
else:
return False
tries = 0
while tries < 3:
pin = input("please enter your pin code")
if verify_pin(pin):
print("Correct")
break
else:
print("Incorrect.Please enter again: ")
tries +=1
You are having syntax & indent issues kindly check the below code
def verify_pin(pin):
if pin == "1234":
return True
else:
return False
tries = 0
while tries < 3:
pin = input("please enter your pin code")
if verify_pin(pin):
print("Correct")
break
else:
print("Incorrect.Please enter again: ")
at = 2 - tries
print("You Have %s More Attempt Remaining" % at)
tries += 1
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make a password system is python but when I tried to compere the user password to the right password I get an exception
'int' object is not subscriptable
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!"), time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = 1234
if (user_pass[0]) == str(password[0]):
print("the first number is correct")
else:
print("the first number is wrong!")
exit()
A couple of things here;
Firstly you need to indent your if not i.isdigit() block:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
You will probably get an exception otherwise.
For your issue; it looks like you are setting the value of password = 1234 which is a integer. You can set this to password="1234" or str(password)[0].
the error occurs because in the line (user_pass[0]) == str(password[0]) you are trying to take the first character in an integer value, you can do this only with strings, so to fix your problem you should modify this (user_pass[0]) == str(password[0]) to this: str(user_pass)[0] == str(password)[0]
so the script should look like this:
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!")
time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = 1234
if str(user_pass)[0] == str(password)[0]:
print("the first number is correct")
else:
print("the first number is wrong!")
exit()
I've tested your code and formatted it again. there was some minor issue regarding indent and string casting, check this out
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!"), time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = "1234"
if (user_pass[0]) == password):
print("the first number is correct")
else:
print("the first number is wrong!")
exit()
In the beginning stages of learning Python and I've hit a bit of a snag
I'm trying to create a program that asks for a specific username and password. After 6 incorrect attempts, it will quit the program. Sample code works fine when I put in the correct info. The issue I'm having is when the username is correct but the password is not. I want it to print that the "password doesn't match" and re-ask for the password. It takes me back to the beginning of the program and asks for my username again. Any ideas to solve this? Thank you in advance!
Code can also be found here: https://pastebin.com/4wSgB0we
import sys
incorrect = 0
max_tries = 6
choices = ['Drake', 'swordfish']
run = True
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()
If it didn't help you solve the problem.
I will modify.
When your user is correct, you should leave While.
If you do not leave While, the user account will be asked again.
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
break
while incorrect < max_tries:
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I have to write a code that will execute the below while loop only if the user enters the term "Cyril".
I am a real newbie, and I was only able to come up with the below solution which would force the user to restart the program until they enter the correct input, but I would like it to keep asking the user for input until they input the correct answer. Could anybody perhaps assist? I know I would probably kick myself once I realise there's a simple solution.
number_list = []
attempts = 0
name = False
number = 0
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
else:
print("\nThat is incorrect, please restart the program and try again.\n")
if name:
number = int(input("Correct! Please enter any number between -1 and 10: "))
while number > -1:
number_list.append(number)
number = int(input("\nThank you. Please enter another number between -1 and 10: "))
if number > 10:
print("\nYou have entered a number outside of the range, please try again.\n")
number = int(input("Please enter a number between -1 and 10: "))
elif number < -1:
print("\nYou have entered a number outside of the range, please try again. \n")
number = int(input("Please enter a number between -1 and 10: "))
elif number == -1:
average_number = sum(number_list) / len(number_list)
print("\nThe average number you have entered is:", round(average_number, 0))
Change beginning of code to:
while True:
name_question = input("You are the President of RSA, what is your name?: ")
if name_question == "Cyril":
name = True
break
else:
print("\nThat is incorrect, please try again.\n")
You can try this even if I don't understand if your question is easy or if I am an idiot:
name_question = input("You are the President of RSA, what is your name?: ")
while name_question != "Cyril":
name_question = input("You are the President of RSA, what is your name?: ")
...
Very limited on using python and totally stuck, I've managed to get a while loop running on the code below so that the user can keep entering a code until they put in the correct one.
What I'm now looking to do is add a for loop so that it only asks the user to enter the code (4 wrong digits) 3 times and then locks them out. At the same time it needs a while loop to ensure if the user puts more than or less than 4 digits it continually runs and doesn't lock them out.
I just cant get the for loop and while loop working at the same time and don't know what I'm doing wrong.
user = ("1234")
valid = False
while not valid:
#for i in range (3):
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
if user != ("1234") :
print ("that is incorrect, please try again")
valid = False
elif len(user) > 4:
print ("That is incorrect, please try again")
valid = False
elif len(user) < 4:
print ("That is incorrect, please try again")
valid = False
else:
print ("You have been locked out!! Alarm!!!!!!")
user = ("1234")
counter = 0
while counter < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if len(user) != 4:
print("I said 4 digits!")
continue
if user == ("1234") :
print("You have cracked the code, well done")
break
print ("that is incorrect, please try again")
counter += 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
else:
print ("Everything is fine.")
I adapted your code a little bit and added a counter variable
user = ("1234")
valid = False
counter = 0
while not valid:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == ("1234") :
print("You have cracked the code, well done")
valid = True
break
elif len(user) != 4:
print ("That is incorrect, please try again")
else:
print ("that is incorrect, please try again")
counter = counter + 1
if counter == 3:
print ("You have been locked out!! Alarm!!!!!!")
#Do stuff to actually abort here...
It counts up if there is a wrong answer now
the inner loop is just for valid input:
user = '1234'
locked = False
miss_cnt = 0
while True:
while True:
ans = raw_input('User -> ')
if len(ans) == 4 and ans.isdigit():
break
if ans != user:
miss_cnt += 1
if miss_cnt >= 3:
locked = True
break
else:
break
I left out the prints for clarity of flow
The following code should work for you.
answer = "1234"
valid = False
count = 0
while not valid and count < 3:
user = input("Hello, welcome! Please enter a four digit passcode to open the safe: ")
user = user.upper()
if user == answer:
print("You have cracked the code, well done")
valid = True
elif count < 2:
print ("that is incorrect, please try again")
else:
print ("You have been locked out")
count += 1
I took the () off of the strings because that would make them sets so the if statement would never be true, because sets don't equal string inputs.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I tried to create a username and password program for my family, but when I open it it says:
Welcome.
Denied!!!
Press enter to quit.
Can anyone solve my problem? The code is below:
print ("Welcome.")
username = ("Please enter your username.")
if username == ("mom, savanna, joseph"):
print ("Granted.")
password = input ("Please enter your password.")
if password == ("1975, 2000, jesus"):
print ("Granted.")
question = ("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
if question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input ("press enter to quit")
Your primary issue is on this line:
username = ("Please enter your username.")
I presume you mean to have an input function call there.
username = input("Please enter your username.")
That will solve your immediate rejection issue.
You also have the same issue on this line:
question = ("Do you like it?")
Which should also be:
question = input("Do you like it?")
Here's the thing:
You are new to code. We can see that here. However, there is always room for improvement and you can learn from mistakes. Some people make odd code sometimes ;)
I have created a working model for you to see where you went wrong.
print ("Welcome.")
username = input("Please enter your username.")
if username in ("mom", "savanna", "joseph"):
password = input("Please enter your password.")
if password in ("1975","2000","jesus"):
print ("Granted.")
question = input("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
elif question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
break
You typed question = ("Do you like it?") without the input. This is important since it actually lets the user type something.
You wrote if username == ("mom,savanna,joseph")
this means that if the username is mom,savanna,joseph then you get in. obviously you wanted only one of these to get in. the Boolean operator or can help a lot in this situation.
Notice how I used elif instead of if. Python can only have one if and one else. but as many elifs as you want. It means else-if.
EDIT:
After reading Joel's comment, I noticed that you probably want Mom's password to be 1975, Savannah's to be 2000, and Joseph's to be jesus. How do you think you can do that by using my code given here?
I'm assuming you want to have 3 different usernames, and mom's password to be 1975 etc.
password = {"mom":"1975", "savanna":"2000", "joseph":"jesus"}
print ("Welcome.")
username = input("Please enter your username.")
if username in password: #if x in dict returns True if dict has the key x
print ("Granted.")
mypassword = input ("Please enter your password.")
if mypassword == password[username]:
print ("Granted.")
answer = input("Do you like it?")
if answer == ("yes"):
print ("I thought you would.")
elif answer == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input("press enter to quit")
You may want to put a loop around it so that it doesn't have to get restarted if there's a bad entry.
you are asking if username == ("mom, savanna, joseph") instead of if username in ("mom, savanna, joseph")
if you entered in "mom" for username when it asked you, it would be like comparing this
if "mom" == ("mom, savanna, joseph"):
("mom, savanna, joseph") and "mom" are not equal
to check if an item is in a list use the in keyword
>>> x = [0, 1, 2, 3, 4]
>>> 3 in x
True
you also did the same thing when checking if password ==
also #Alexander O'Mara is correct, you never did the input() for username