I am new to programming and I'm trying to make an option for the user to exit upon "yes" or y ,or "no" or "n", but I am having the worst luck in trying to do this. Could someone help me point out my error and hint at a better way to do this? I would really appreciate the assistance. Thank you.
I apologize about my vague posting. Let me be a little more clear in my question. Using two while loops to execute my program in a loop, I want to give the user a choice to whether they want to leave or redo the program. The program, however, doesn't exit properly, even though I've stated that "n" specifically is set to terminate the program. The code will, however, will loop back when I request or don't request to redo the main program, whether I enter "y" or "n".
I am confused as to what exactly is wrong with my loop, as it should close when I enter "n". What exactly is the problem with my loop's exit?
# Blah Blah Blah. Main program inserted here.
replay = input("Do another Calculation? (y/n)").lower()
if replay in ('y','n'):
if replay == 'y':
.lower should be
.lower() is a function, and calling it without parentheses doesn't do anything:
>>> string = 'No' >>> string.lower <built-in method lower of str object at 0x1005b2c60> >>> x = string.lower >>> x <built-in method lower of str object at 0x1005b2c60> >>> x = string.lower() >>> x 'no' >>>
Also, you are checking for equality in
replay == input(...). You just want a single
= to assign:
>>> result = 0 >>> result == 4 False >>> result = 4 >>> result == 4 True >>>
You also have an unwanted
print replay in your second
while True loop.
This is a suggestion: instead of using
replay in ("no, "n"), which is very unpythonic, use the built-in method
startswith(char) to see if it starts with that character:
>>> string = "NO" >>> string.lower().startswith("n") True >>> string = "yeS" >>> string.lower().startswith("y") True >>>
This also works for input like
Here is your edited code:
a = int(input("Enter the first number :")) b = int(input("Enter the second number :")) print("sum ---" + str(a+b)) print("difference ---" + str(a-b)) print("product ---" + str(a*b)) print("division ---" + str(a/b)) input() while True: print("Do you want to try again?") while True: replay = input("Do another Calculation? 'y' for yes. 'n' for no.").lower() print(replay) if replay.startswith('y') == True: break if replay.startswith('n') == True: exit() else: print("I don't understand what you wrote. Please put in a better answer, such as 'Yes' or 'No'")
I see some syntax errors:
print replay should be
if replay in ("yes","y") should be
if replay in ("yes","y"):
if replay in ("no","n") should be
if replay in ("no","n"):