How can I make the program stop if the input is invalid? - python

I need to know how can I make my program continue with the login ONLY if the entered username is valid, but if an incorrect username is entered it should stop, but the break function just doesn't work.
I am a beginner, and I am truly sorry about posting about something this simple, but I cant get it to work and I cant find a direct answer elsewhere.
Code:
if a == x:
print('entered username is valid')
else:
print('entered username is invalid')
break
I tried using {}, and it didn't quite work; it said something about just not working properly but the brackets don't work in any scenario.

while a!="":
if a!=x:
print("username invalid")
break
else:
print("username login valid")
b=str(input("enter password"))
if b==y:
print("logged in successfully")
break
you can work with something similar, break are only for loops , you should integrate it with while/for loop, for this example we entered in a loop that loos on while your "a" username input is not empty

break is for loops. If you want your program to stop, try replacing break by sys.exit().
Of course, you'll need to add at the beginning of your program:
import sys
because sys.exit() is a function of module sys.

Related

A Loop I can never return from

So I have been tasked with creating a Login function using an intake from a pickle file, my only issue (that I have noticed) so far is that I can never get out of the loop.
for counter in range(len(Users)):
UserN = input("Username: ")
if UserN in Users[counter]:
PassW = input("Password: ")
if PassW in Users[counter]:
print("User Authenticated")
break
else:
attempt = 1
while attempt != 4:
print("Password Incorrect | Attempt", attempt)
PassW = input("Password: ")
if PassW in Users[1]:
print("User Authenticated")
MainMenu()
else:
attempt = attempt + 1
if attempt == 4:
print("\nToo many attempts, you are locked out")
exit()
else:
print("\nUser not found!\n")
If the user is authenticated, the count of the attempt will stop increasing, but the condition for the while-loop is stop is attempt == 4, so it will be stuck until the user has typed in the wrong password 4 times.
To fix it, either add a variable authenticated before the while-loop and initialize it as False, then set it to True once the user has successfully been authenticated.
attempt = 1
authenticated = False
while attempt != 4 and !authenticated:
...
if PassW in Users[1]:
...
authenticated = True
Or if you don't want a new variable, simply break by
if PassW in Users[1]:
...
break
to break the loop
If you the password is found, you call another function but you never exit from the loop. You should add a break statement.
You can add a break statement under
MainMenu()
break;
The logic in your code seems quite wonky.
This code assumes that the username is the first appearing in Users; if the second user logs in, they need to enter their name twice, the third user 3 times, and so on. If you mistype your name on your "turn", you won't be able to log in at all.
I would suggest the following structure:
Turn your variable "Users" into a dictionary, mapping user name to password.
Ask the user name.
If the user name does not appear, either stop or loop (you might want to prompt to ask whether they want to try again or not, or just let them press ctrl-D to stop (and catch the ensuing EOFError or KeyboardInterrupt (which happens if they press ctrl-C instead).
Some other issues, that are not as crucial for this question but good guidelines:
Use proper style conventions. Variable names should not start with upper case characters. Same for goes for functions. It should be users, passw, main_menu().
You really should not store passwords in a pickle file; that is obfuscation rather than security. Have a look at https://www.geeksforgeeks.org/getpass-and-getuser-in-python-password-without-echo/ for better practices.
When you say the user is locked out, nothing actually happens. They are not really locked out; they could just try again. That means you can just create a bit that brute-forces password guesses
Let them enter the password, with a maximum number of guesses.
A good rule is to test for attempt > 3 instead of attempt == 4. This does not make a difference here, but in larger functions, it's often good practice to make the test a bit "wider".

How do I use an elif statement properly?

Please don't judge me.. I've only been working with Python for a month now.
While laying in my bed I thought of making this and created it in a few minutes but I made to many else and if statements and my code just looks so messy, I kept adding things that weren't needed..(For fun :D)
Anyways, here is my code.. If you could tell me how to use the "elif" statements properly that'd be awesome.(I'm still learning python)
Question: I've tried using an elif statement multiple times and I keep getting an error. How do I fix this?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")
We can't debug code you haven't posted, and (as is to be expected - you are on a learning exercise here, and there's a lot to think about) your program structure isn't very helpful. For example, when the user enters non-matching passwords you tell them about it, but nevertheless continue to ask them for their username. Don't worry about this, you will soon learn how to fix it.
Since you ask about the elif, it is basically a syntax abbreviation for else if that avoids going to multiple indentation levels. Suppose you wanted a value of '1' or '2' to take different actions, and to declare other values invalid. You could write
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Note that the different actions are at different indentation levels. The more cases you have to consider, the more levels of indentation you have to introduce. So it's generally felt to be more readable to write
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Now all the actions and decisions are at the same indentation levels. That's pretty much all there is to it. If you leave the else case off then you won't take any actions at all, so it's normally used to specify the default action, in this case raising an exception.
PS: If you want to be sure the user has entered two matching passwords before you proceed, look at the while loop, which allows you to repeat a set of actions until some condition (in this case the passwords being equal) is true.
Here is an example if if/elif/else statement in python3:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
You can find more information here : https://docs.python.org/3/tutorial/controlflow.html
EDIT:
As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)
So using Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
Though what is this error you're getting, we can't really help you without it.

Simple password check with limited retries

I'm trying to do a simple password check with limited retries.
If user keys in wrong password, program prompts to try again (3 retries).
After 3 failed retries, program prompts user has reached maximum retries.
If User keys in correct password, program will "grant access".
import sys
print (sys.version)
pssw = ''
attempt = 0
print('Please key in your password.')
while (pssw != "remember") and (attempt < 3):
pssw = input()
attempt = attempt + 1
print ('No that is not correct. Try again.')
if attempt == 3:
print ('Sorry you have reached maximum number of attempts')
break
if (pssw == "remember"):
print('Access Granted!')
Problem #1
Expectation: After keying in the correct password "Remember", program should print output "Access Granted"
But program output:
3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
Please key in your password.
remember
No that is not correct. Try again.
Access Granted!
Problem #2
Expectation: After keying in the correct password "Remember" on the last try, program should print output "Access Granted"
But program output:
Please key in your password.
test
No that is not correct. Try again.
test
No that is not correct. Try again.
remember
No that is not correct. Try again.
Sorry you have reached maximum number of attempts
What am I doing wrong?
I will just explain your errors because someone posted another code approach.
I think it's important that you understand your erros and do not just copy another code.
First, the line break is incorrect because a break cant be outside a loop, use sys.exit() instead.
Problem #1:
If you enter the right password your program will exit the loop and execute the next statements:
print ('No that is not correct. Try again.')
if attempt == 3:
print ('Sorry you have reached maximum number of attempts')
break
if (pssw == "remember"):
print('Access Granted!')
So it will print "No that is not correct. Try again.".
Check if attempt is equal to 3. It isn't because you entered the right password at the first attempt.
Check if password is equal to "remember". It is, so program will print "Access granted".
Problem #2:
Your second output is incoherent with the code you posted.
Normal output for the code you posted is:
Please key in your password.
test
test
remember
No that is not correct. Try again.
Sorry you have reached maximum number of attempts
This is the normal output for the code you posted, but it's wrong anyway.
It's because if tou type an incorrect password, the loop will just continue and thus ask again for your password without printing anything.

How do I add a retry option to a function in Python?

Pretty new to Python, trying to create a simple login system here (has to be done this way). I've already defined a user() function which asks for the username and checks its validity. This function starts by calling the user function. Here is the main part:
user()
if user in userlist:
while True:
pass = raw_input("Enter password, or X to retry: ")
if pass == 'X':
break
if userlist[user] == pass:
break
else:
print "Invalid password."
I want the function to loop back to asking for username input if X is entered. The rest of it works fine but as it stands, entering X just ends the function and doesn't loop it back to the start. Is this just not possible or can I rewrite it to work? I assume I'd need to include user() into the loop but I've encountered various errors while trying.
You intentionally say to exit the loop if the user enters X by using the break statement. That's why the loop is exiting. Instead of break use continue.
if password == 'X':
continue
This will start the loop over again at the top.
As another user notes, you can't use pass as a variable name. The code you posted clearly isn't the code you're actually running. Anyway, I've assumed that you really used the name password.
Don't use pass as a variable name because it clobbers the builtin pass. What you want is
if passwd == 'X':
continue #restart at top of loop
You'll have to do:
if password == 'X':
continue #restarts loop at while

Exit while loop by user hitting ENTER key

I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting <Return> only. So far I have:
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my program
if User == # Not sure what to put here
Break
else
running == 1
I have tried: (as instructed in the exercise)
if User == <Carriage return>
and also
if User == <Return>
but this only results in invalid syntax.
Please could you advise me on how to do this in the simplest way possible.
Thanks
I ran into this page while (no pun) looking for something else. Here is what I use:
while True:
i = input("Enter text (or Enter to quit): ")
if not i:
break
print("Your input:", i)
print("While loop has exited")
The exact thing you want ;)
https://stackoverflow.com/a/22391379/3394391
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.
If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.
Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link
I think the following links would also help you to understand in much better way.
python cross platform listening for keypresses
How do I get a single keypress at a time
Useful routines from the MS VC++ runtime
I hope this helps you to get your job done.
Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.
This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.
import time
import threading
# set global variable flag
flag = 1
def normal():
global flag
while flag==1:
print('normal stuff')
time.sleep(2)
if flag==False:
print('The while loop is now closing')
def get_input():
global flag
keystrk=input('Press a key \n')
# thread doesn't continue until key is pressed
print('You pressed: ', keystrk)
flag=False
print('flag is now:', flag)
n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)
if repr(User) == repr(''):
break
a very simple solution would be, and I see you have said that you
would like to see the simplest solution possible.
A prompt for the user to continue after halting a loop Etc.
raw_input("Press<enter> to continue")
user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):
print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
import sys #import
sys.exit(0) #exit program
'''
#(not user_input) checks if user has pressed enter key without entering
# number.
#(int(user_input)<=0) checks if user has entered any number less than or
#equal to zero.
'''
Here is the best and simplest answer. Use try and except calls.
x = randint(1,9)
guess = -1
print "Guess the number below 10:"
while guess != x:
try:
guess = int(raw_input("Guess: "))
if guess < x:
print "Guess higher."
elif guess > x:
print "Guess lower."
else:
print "Correct."
except:
print "You did not put any number."
You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5
running = 1
while running == 1:
user = input(str('Enter <Carriage return> only to exit: '))
if user == '':
running = 0
else:
print('You had one job...')
I recommend to use u\000D. It is the CR in unicode.
Here's a solution (resembling the original) that works:
User = raw_input('Enter <Carriage return> only to exit: ')
while True:
#Run my program
print 'In the loop, User=%r' % (User, )
# Check if the user asked to terminate the loop.
if User == '':
break
# Give the user another chance to exit.
User = raw_input('Enter <Carriage return> only to exit: ')
Note that the code in the original question has several issues:
The if/else is outside the while loop, so the loop will run forever.
The else is missing a colon.
In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
It doesn't need the running variable, since the if clause performs a break.
If you want your user to press enter, then the raw_input() will return "", so compare the User with "":
User = raw_input('Press enter to exit...')
running = 1
while running == 1:
Run your program
if User == "":
break
else
running == 1
The following works from me:
i = '0'
while len(i) != 0:
i = list(map(int, input(),split()))

Categories

Resources