简体   繁体   中英

Function if only accepts one input

My code is here: http://pastebin.com/bK9SR031 . I was doing the PygLatin exercise on Codecademy and got carried away, so most of it is... beginner.

Sorry that it's really long. The problem is that when the [Y/N] questions come up, no matter what I type in it behaves as if I input "yes".

One of the relevant excerpts:

def TryAgain():
    repeat = raw_input("\nStart over?[Y/N] ").lower()
    if repeat == "y" or "yes" :
        print "OK.\n"
        PygLatin()
    elif repeat == "n" or "no" :
        raw_input("\nPress ENTER to exit the English to Pig Latin Translator.")
        sys.exit()
    else:
        TryAgain()

No matter what I input, it prints "OK." and then starts the PygLatin() function again.

The condition in your first if statement:

 if repeat == "y" or "yes":
    print "OK.\n"
    PygLatin()

always evaluates to True , regardless of the value of repeat . This is because "Yes" is not an empty string (it's boolean value is True ), so the or always results in True . One way to fix it is with:

if repeat == "y" or repeat == "yes":
    print "OK.\n"
    PygLatin()

another one (as sateesh mentions below) is:

if repeat in ("y","yes"):
    print "OK.\n"
    PygLatin()

You should also change the else condition accordingly

Also it is better to do if check in below manner:

if repeat in ("y","yes"):
    ...
elif repeat in ("n","no"):
    ...

Comparing by keeping all possible values in a tuple (list) makes the code readable. Also if there are more values to be compared with you can create a tuple (or list) to store those values and make comparison against the stored values. Say something like below keeps code more readable:

acceptance_values = ('y','yes')
    ...
if repeat in acceptance_values :
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM