Repeat Loop upon False - python

The function below calls for the input command and check if str.isalnum().
def enterPass(str):
x = raw_input("enter password Alpha or Alphanumeric! 'No_Space' :")
if x.isalnum():
print "saved"
else:
print "try again"
return;
Followed from the above is the below function, which exists when the function enterPass has been called 3 times.
_try = 1
while (_try <= 3):
enterPass("password")
_try += 1
My intention was that upon entering password it should verify if it is Alpha-Numerics or not. If so, it should prompt "Saved" and quit, if not then it should ask for the password again, and if the user cannot get the password right 3 times, the program shoudl quit.
The problem I am facing is that I am unable to quit this program once it had successfully accepted the isalnum() with "Saved" prompt. It is going again in the loop asking to enter my password again. Please suggest how I can make this function work as intended, and possibly more efficienty.
The above program is just for academic purpose and has no useful application at present.

A function is probably not needed in this case, as you can then use break:
tries = 0
while tries < 3:
x = raw_input("Enter password Alpha or Alphanumeric! No spaces! ")
if x.isalnum():
print "Saved"
break
print "Try again"
tries += 1
Here's a test:
Enter password Alpha or Alphanumeric! No spaces! Hi!##
Try again
Enter password Alpha or Alphanumeric! No spaces! !##!##
Try again
Enter password Alpha or Alphanumeric! No spaces! ####
Try again
>>>
Enter password Alpha or Alphanumeric! No spaces! No!
Try again
Enter password Alpha or Alphanumeric! No spaces! Okay
Saved
>>>

You could import sys and do sys.exit(0)
import sys
if x.isalnum():
print "saved"
sys.exit(0)
Now sys.exit will give you a bunch of errors when it's exiting the program when running in an IDLE, ignore those because in the actual final program they will not appear.
But that is if you want to terminate the whole program. If you simply want to break out of the loop and continue the program with something else you can do
if x.isalnum():
print "saved"
break
Break must also be in a loop for it to work.

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".

Noob's python journey pt. 1: Functions and commands that jump everywhere [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
So, noob here, now that's out of the way let's get to the problem shall we?
(First post, ever)
So, my code (below) is quite inconsistent. I have just begun, about two days ago, and I'm dying to become better and love all kinds of critique, so unload all you've got.
When the user enters "login" to login he gets prompted to enter the username (a separate function creating a global variable for the password function to use as the welcoming name.) and is immediately redirected to the password check. Here there are two outcomes: 1. The user types in the correct password, the user will be "let in:" "Welcome " + username + "." 2. The user types in the wrong password/types anything that isn't the password: the user is sent back to the username check. But what happens for me is that the Python instead jumps back to the intro code and exits the program with: "Invalid input." And it seems as if the program goes to the password function, does its thing and immediately reverts to the former function.
Tl:Dr: Functions don't loop as they should, instead return to the previous function, thus ignoring the action I wrote.
Excuse me for the wall of text, and please, please please for the love of god or anything, don't hit me with a wall of code and "Fixed!" I'm very new and barely understand anything outside this patch of code which I myself wrote with my new gained experience. Otherwise it will end up with a [ctrl + c --> ctrl + v] situation and I really, really want to learn, not copy. So if you think you have what it takes, please do your best, everything is appreciated :)
Ps: Tips & Tricks are valuable for me!
PPs: If you want more code, just say it and I'll do my best.
Changes in the login screen:
choice = input
if input blah blah:
"function"
creating a whole function for it
moving the commands around
messing with other codes
# Password check.
def password_check():
print("Please enter your password")
print("")
password = input("")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")
Your if statement checking password was in the global area and not inside your function.
# Password check.
def password_check():
password = input("Please enter your password\n\n ")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")

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 to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

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