Jodo1992 Jodo1992 - 2 years ago 55
Python Question

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

I have a

method in Python 2.7.11 that (after its first execution) will ask if the user wants to continue
. The response of
re-executes the while loop I instantiated in
just fine, and erroneous inputs are taken into account and the question is re-asked. However, when the user enters
, it does not print
, it instead exits out of the loop without even reaching the
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.'
continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')

if __name__ == "__main__":

I thought maybe my issue was
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
being printed if I input
, or infinite unresponsiveness if I input

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download