Jodo1992 Jodo1992 - 7 months ago 5
Python Question

Why isn't my if statement executing its print statement Python 2.7.11

I have a

main
method in Python 2.7.11 that (after its first execution) will ask if the user wants to continue
(y/n)
. The response of
'y'
re-executes the while loop I instantiated in
main
just fine, and erroneous inputs are taken into account and the question is re-asked. However, when the user enters
'n'
, it does not print
'Goodbye.'
, it instead exits out of the loop without even reaching the
print
statement. Here is my code:

def main():

continue = 'y' # Default for the first execution

while continue == 'y':
# A bunch of execution code here for the program...

# After executing rest of code
continue = raw_input('Do you wish to continue? (y/n): ')

while continue != 'y' and continue != 'n':
if will_continue == 'n':
print 'Goodbye.'
else:
continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')


if __name__ == "__main__":
main()


I thought maybe my issue was
and
in
while continue != 'y' and continue != 'n':
, so I changed it to
while continue != 'y' or continue != 'n':
, but this keeps me in an infinite loop of
'Goodbye'
being printed if I input
'n'
, or infinite unresponsiveness if I input
'y'
.

Any ideas as to why that
print 'Goodbye.'
statement won't execute before terminating the
main
?

Answer

You're asking the user for input in the else block. If the user inputted 'n', the while block will terminate in the next iteration, causing your if will_continue == 'n' to never execute. A quick fix for it would be to place your if block outside of the inner while loop.

Alternatively, you can eschew the if block and simply have the program print 'Goodbye' at the end regardless of what happens.