Is there a way to set a 30 second timer to verify a username for a program before it returns back to the start line, and requests for the user to input the name again? This is what I have so far:
print("")
verifyp1loop = True
while verifyp1loop==True:
verifyp1 = input("Please input Player 1's username. ")
verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
if verifyp1confirm == "y":
print("Username confirmed.")
verifyp1loop=False
else:
print("Username denied.")
verifyp2loop = True
while verifyp2loop==True:
verifyp2=input("Please input Player 2's username. ")
verifyp2confirm=input("Are you sure you want this to be your username? y/n ")
if verifyp2confirm == "y":
print("Username confirmed.")
verifyp2loop=False
else:
print("Username denied.")
I'm very new to this and any help would be appreciated :)
Lightweight solution:
no loops
no threads
just example how to implement timeout
import time
class Verify(object):
def __init__(self,timeout):
self.timeout = timeout
self.verification = None
def verify(self):
self.verification = None
start_verification = time.time()
verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
end_verification = time.time()
if (end_verification-start_verification)>self.timeout:
print('Denied')
self.verification = 0
else:
print('OK')
self.verification = 1
>>> ver=Verify(3)
>>> ver.verify()
Are you sure you want this to be your username? y/n y
OK
>>> print(ver.verification)
1
>>> ver.verify()
Are you sure you want this to be your username? y/n y
Denied
>>> print(ver.verification)
0
Note same answer, different output
Implementation:
ver=Verify(3)
while ver.verification == None or ver.verification ==0:
ver.verify()
Related
while True:
print('enter username: ')
username = input()
if username.lower() != 'joe':
print("imposter!")
continue
print(f'Hello {username.capitalize()}')
print('enter password: ')
password = input()
tries = 0
if password != 'Water':
tries += 1
continue
if tries == 3:
print("3 strikes, you're out")
quit()
else:
break
print("access granted")
Trying to make a username and password prompt. I am trying to give infinite tries to username entries, and only 3 chances for a correct password. When you type in the correct user name and password everything works fine. BUT when typing in the incorrect password, it loops back up to enter username, and the 'tries' counter does not work. python noob trying to learn using Automate The Boring Things in Python
You could try restructuring your code like the below:
import sys
access = False
while not access:
username = input('Enter username: ')
if username.lower() != 'joe':
print("imposter!")
continue
else:
print(f'Hello {username.capitalize()}')
for i in range(3):
password = input('Enter password: ')
if password == 'Water':
access = True
break
else:
print("3 strikes, you're out")
sys.exit()
print("Access granted")
You reset tries = 0 within the loop.
This is basic python. I want the user to enter the displayed username and password 3 times. When I entered an incorrect input in the first and second tries, the code in elif functions correctly but when I incorrectly entered it in the third try, it doesn't run the statement in the elif. Can you explain why this is happening?
The code is supposed to exit when entered the wrong input. I also want to make the user enter the correct input for 3 times then it will print the welcome.
username = "Username"
password = "Password"
tries = 0
print("Your username: Username")
print("Your password: Password")
print(" ")
enterusername = str(input("Enter your username:"))
enterpassword = str(input("Enter your password:"))
while tries < 2:
if (password == enterpassword and username == enterusername):
enterusername = str(input("Enter again your Username:"))
enterpassword = str(input("Enter again your password:"))
tries = tries + 1
else:
exit("Password or username is incorrect.")
print("Welcome")
It's because you set
while tries < 2:
on the third try, tries=2, so your while loop doesn't run. Change it to while tries < 3
Your logic goes as follows:
Ask for input.
In loop:
Validate last input.
Ask new input.
You can see from this that the input form the last iteration will not be validated. You need to either:
Validate the first input before the loop and change the loop's order.
Validate the last input after the loop.
1
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
if (password == enterpassword and username == enterusername):
while tries < 2:
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
if password == enterpassword and username == enterusername:
tries += 1
else:
exit("Password or username is incorrect.")
else:
exit("Password or username is incorrect.")
2
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
while tries < 2:
if password == enterpassword and username == enterusername:
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
tries += 1
else:
exit("Password or username is incorrect.")
if password == enterpassword and username == enterusername:
print("Welcome")
else:
exit("Password or username is incorrect.")
I made a few small changes in your code:
input always returns a string so there is no need to convert with str().
x = x + 1 is equivalent to x += 1.
Your condition were complementary so there is no need to write the opposite in an elif - just use else.
To avoid the repeated conditions, reverse the logic: check the input in the while condition and count the tries inside the loop:
enterusername = input("Enter your username:")
enterpassword = input("Enter your password:")
while password == enterpassword and username == enterusername:
if tries == 2:
print("Welcome")
break
enterusername = input("Enter again your Username:")
enterpassword = input("Enter again your password:")
tries += 1
else:
exit("Password or username is incorrect.")
This uses the while/else construct - the else will only be executed if the loop terminated without reaching a break.
You should put
while(tries <= 2):
...
or
while(tries <3):
...
So the exercise I'm doing goes:
086 Ask the user to enter a new password. Ask them to enter it again.
If the two passwords match, display “Thank you”. If the letters
are correct but in the wrong case, display th emessage “They must be in
the same case”,otherwise display the message “Incorrect”.
My attempt looks like this:
passw = input("Enter password: ")
passw2 = input("Enter password again: ")
if passw == passw2:
print("Thank you.")
elif passw != passw2 and passw.lower == passw2.lower:
print("They must be in the same case.")
else:
print("Incorrect.")
That didn't give me the result I was hoping for though.
This should be really simple but as you can tell I'm a beginner :)
Thank you in Advance!
Marcel
That passw.lower is a method, the method itself, you may call it to have the password in lowercase. Also remove passw != passw2 in second ìf that's mandatory True
if passw == passw2:
print("Thank you.")
elif passw.lower() == passw2.lower():
print("They must be in the same case.")
else:
print("Incorrect.")
More
passw = "Abc"
print(passw.lower(), "/", type(passw.lower()))
# abc / <class 'str'>
print(passw.lower, "/", type(passw.lower))
# <built-in method lower of str object at 0x00000202611D4730> / <class 'builtin_function_or_method'>
The problem is that your elif condition always evaluates to True:
elif passw != passw2 and passw.lower == passw2.lower:
str.lower is a function, and comparing a function with the same function logically ends up being True. You have to call the functions instead and compare their results. Additionally, you are doing comparing passw and passw twice : once you check if they are the same in the if condition, and once you check if they are not the same in the elif condition. This is useless, because the elif condition will only ever be executed when the if condition was False. Following the working code:
passw = input("Enter password: ")
passw2 = input("Enter password again: ")
if passw == passw2:
print("Thank you.")
elif passw.lower() == passw2.lower():
print("They must be in the same case.")
else:
print("Incorrect.")
Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?
import colorama
colorama.init()
print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"
#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"
def get_file_contents(file_path):
return [line.strip() for line in open(file_path)]
scoreslist = get_file_contents(scoreslist_path)
def add_file_contents(file_path, contents):
with open(file_path, "a") as file:
file.write(contents)
def login_user(new_account=False):
usernameslist = get_file_contents(users_path)
passwordslist = get_file_contents(passwords_path)
if new_account:
response = 'y'
else:
response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
print("-"*50)
#If user has an account:
if response == "y":
goodlogin = False
username = input("Please enter your username: ")
password = input("Please enter your password: ")
for id in range(len(usernameslist)):
if username == usernameslist[id] and password == passwordslist[id]:
goodlogin = True
if goodlogin:
print(print_in_green + "Access granted!" + print_default)
#Ask if user would like to view leaderboard
leaderboard = input("Would you like to view the leaderboard (y/n)? ")
#If thet want to see scores:
if leaderboard == "y":
print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
for c in range(0, len(scoreslist)-1):
max = scoreslist[c]
index_of_max = c
for i in range (c+1, len(scoreslist)):
if (scoreslist[i] > max):
max = scoreslist[i]
index_of_max = i
aux = scoreslist[c]
scoreslist[c] = max
scoreslist[index_of_max] = aux
#print(scoreslist)
print(*scoreslist, sep = "\n")
print("-"*50)
#If they don't want to see scores:
else:
print("OK. Thanks for loging in!")
else:
print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)
#If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
login_user()
The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
print("Ok, please continue!")
else:
print("This username is already taken. Please try another.")
...
What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.
What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.
Here's what should work for you:
...
for id in range(len(usernameslist)):
if newusername != usernameslist[id]:
goodlogin2 = True
else:
print("This username is already taken. Please try another.")
if goodlogin2 = True:
print("Ok, please continue!")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
...
It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration.
Try this instead:
# If user does not have account:
else:
goodlogin2 = False
newusername = input("What is your new username? ")
if newusername in usernameslist:
print("This username is already taken. Please try another.")
else:
goodlogin2 = True
print("Ok, please continue!")
# for id in range(len(usernameslist)):
# if newusername != usernameslist[id]:
# goodlogin2 = True
# print("Ok, please continue!")
# else:
# print("This username is already taken. Please try another.")
newpassword = input("What is your new password? ")
newpasswordagain = input("Please enter your new password again.")
if newpassword == newpasswordagain:
print("Please follow the instructions to log in with your new credentials.")
add_file_contents(users_path, '\n' + newusername)
add_file_contents(passwords_path, '\n' + newpassword)
login_user(new_account=True)
else:
print("Your passwords do not match. Please try again.")
This produces the following output for a user with no previous account who enters a name which has not been used:
--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username:
I'm making login/signing section for my code. I have 2 issues with it. I need help:
First question Yes or No functions well until other character entered. While loop is not accepted for some reason. How to get back to beginning until Y or N entered?
I would like to store dict with usernames and passwords as CSV file sorted in two columns not rows. How to do it.
Thanks
Here is the code....
# CREATING START DICTIONARY
users = {"guest": "guestpass", "admin": "adpass"}
status = input("\rAre you a registered user? Y / N? ").upper()
while status != "Y" and status != "N":
print ("Please enter Y or N")
# NEW USER
if status == "N":
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print("Login name already exist! Please, choose another one.\n")
else:
createPass = input("Create password: ")
retypePass = input("Retype password: ")
while True:
if createPass != retypePass:
print("\nPassword error!\n")
else:
users.update({createLogin : createPass})
print("\nNew user created! Welcome to ARR!\n")
break
import csv
writer = csv.writer(open('UsersFile.csv', 'wb'))
for key, value in users.items():
writer.writerow([createLogin, createPass])
# LOGIN EXISTING/NEW USER
elif status == "Y":
while True:
loginName = input("Enter login name: ").lower()
if loginName not in users:
print("User doesn't exist! Please enter existing name or sign-in.")
print("----------------------------------------------------------")
else:
passw = input("Enter password: ")
# LOGIN MATCHES PASSWORD
if loginName in users and passw != users.get(loginName):
print("Wrong password! Please enter username and password again!")
else:
print("Login successful!\n")
break
1) In your y/n while loop you are missing a tab to indent the print statement.
2) https://docs.python.org/2/library/csv.html
Some issues I see so far:
Indentation. print ("Please enter Y or N") should be indented relative to the while statement on the previous line.
Also, the statement if createLogin in users and the following else statement should probably be indented one more level, if they are meant to be within the if status == 'N' statement.
Import statement. Generally, things like import csv would be at the top of the file. Try moving it there and see if it helps.