I'm writing a script that takes in user input at multiple points. If the input is correct, all I need is to break out of the loop and continue. But if it's wrong, what I'm trying to do is delete and then re-prompt for that input. Here is a general case of what I'm working towards:
while True:
test = input("Enter test to check: ")
if test == expected:
break
else:
print("Error: test is incorrect")
#Clear/overwrite test
#Re-prompt for input
I've been doing some research but I haven't found anything that really makes sense to me. Is there a way to delete or overwrite the value entered by the user so that once test is entered again, it's an entirely new value?
If that's very important to you to clear the screen before asking user again for input you could wait some time after displaying error message and then ask user for input again wiping out error message.
import time
expected = 'foo'
while True:
print(' '*30 + '\r', end='')
test = input("Enter test to check: ")
if test == expected:
break
else:
print("Error: {} is incorrect\r".format(test), end='')
time.sleep(2)
If you would like to clear error message and previous input you could use for example os.system('clear').
solution:
else:
print("Error: test is incorrect")
test = input("Enter test to check")
You don't have to 'clear' test as you're reprompting and therefore changing the value of test each time
Why not do something like this
lol=True
while lol:
test = input("Enter test to check: ")
if test == expected:
lol=False
print("Corect!!!")
else:
print("Error: test is incorrect")
Hope it helps
Related
Im new to python and I'm trying to code a python login program. Instead of printing out "Welcome to the database" when the username provided is correct, it printed out both "Welcome to the database" and "Username invalid. Please try again.". May I know which part of my code needs to be corrected?
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
else:
print("Username invalid. Please try again")
You are looping through all the users in the text file and for each of them printing to the console. The thing you probably want could be done like this:
def login():
while True:
loginSucessful = False
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
loginSucessful = True
break
if loginSucessful:
print("welcome to database")
else:
print("Username invalid. Please try again")
You could use a boolean variable to keep track of successful logins like #Michalor did. Or you can use Python's for/else loop to do the same thing without adding a new variable. If the login is successful and you break out of the loop, the "else" statement isn't executed. Using "break" also has the advantage that you don't need to test all of the other users after you have found a successful login.
def login():
while True:
name = input("Name: ")
with open('username.txt', "r")as name_file:
for line in name_file.readlines():
if name == line.strip():
print("welcome to database")
break
else:
print("Username invalid. Please try again")
Of course, this kind of function doesn't provide much security, as you can keep guessing the names in the text file until you find a valid one, or if you can get your hands on the text file itself you can just look the names up. For actual login code, it's probably best to use some kind of login library that handles the security details for you.
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
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()
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.
I have a problem with a program I am making to do with an arithmetic quiz.when I enter a name the quiz should print the welcome message however if I enter a blank or a number then the programme should loop the question but tell the user that they have made an error. I used the try statement and the NameError statement to try and resolve this problem but when I use the function "except" and run it in idle it says that I have an invalid syntax.
here is the code i am trying to fix:
import random
while True:
try:
UserName = input("What is your name:")
except NameError:
print ("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
I have edited the code for the program, but still when I try to run it in Idle it highlights except and then says invalid syntax.
You don't need a try-except to check for an empty string
while True:
UserName = input("What is your name:")
if not UserName:
print("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
This is what the proper indentation should be for the try: except: else: block
import random
while True:
try:
UserName = input("What is your name:")
except NameError:
print("The answer given does not compute!! Try again")
continue
else:
break
print(UserName," welcome to the Arithmetic Quiz.")
caveat (thanks cricket_007) this loop will never end. I had meant this comment to show how the try: indentation should have been for the OP.