Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
jane Avatar asked Jul 04 '26 23:07

jane


2 Answers

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

like image 195
Amelio Vazquez-Reina Avatar answered Jul 07 '26 13:07

Amelio Vazquez-Reina


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 :
    ...
like image 39
sateesh Avatar answered Jul 07 '26 11:07

sateesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!