Reputation: 69
I need to write an encryption program and I'm in the middle of the assignment. Listed below are the instructions for this part. How can I tell python to redo the while loop if they don't enter e,d,or q? My q entry works fine, but as you can see, I need help trying to create a case where if a user enters another character.
Ensure that the user enters ‘e’ or ’d’ or ‘q’ by using a while loop to make them redo any bad entry. StartMenu() should then return their choice back to the main() function, where a variable of main() should catch that return value.
def PrintDescription():
print 'This program encrypts and descrypts messages using multiple \
encryption methods.\nInput files must be in the same directory as this program.\
\nOutput files will be created in this same directory.'
def StartMenu():
print 'Do you wish to encrypt or decrypt?'
print '<e>ncrypt'
print '<d>ecrypt'
print '<q>uit'
def main():
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?! \t\n\r"
PrintDescription()
while True:
StartMenu()
a = raw_input("")
if a!='e' and a!='d' and a!='q':
print 'You must enter e, d or q'
False
break
if a == 'q':
break
Upvotes: 0
Views: 115
Reputation: 132138
Just for the sake of forgoing an extended conversation in comments, this should meet all of your requirements:
def main():
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?! \t\n\r"
PrintDescription()
a = None
while a not in ('e', 'd', 'q'):
if a:
print "Try again!"
else:
StartMenu()
a = raw_input("")
if a == 'q':
sys.exit(0)
What's happening...
The first time through the main function, a will be set to None. A while loop will then start which says to continue running until a is one of the three required letters. Of course, the first time through a is None, so it will enter the while loop. Since a is None, if a:
evaluates to False
. So that block will be skipped. However, the else will be executed and will print the StartMenu. You will then read the user input and decide what to do when the loop starts over. If the criteria is met (ie. a is one of the 'e', 'd', or 'q', then it will not iterate the loop again. However, if a is not in the three letters then another iteration of the loop will begin. This time, however, a is something so if a:
evaluates to True
. Now it prints "Try again!" and does not print the StartMenu. From now on this will continue until one of the three letters is entered.
Upvotes: 2