问题描述:

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.

Edit

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?

My coding

while True:

# Blah Blah Blah. Main program inserted here.

while True:

replay = input("Do another Calculation? (y/n)").lower()

if replay in ('y','n'):

break

print("Invalid input.")

if replay == 'y':

continue

else:

print("Good bye")

exit()

网友答案:

Your .lower should be .lower(). .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 : after 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 naw, or yeah, etc.

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:

1) print replay should be print(replay)

2)if replay in ("yes","y") should be if replay in ("yes","y"):

3)if replay in ("no","n") should be if replay in ("no","n"):

相关阅读:
Top