4/19 - "Simple Errors" - It just keeps asking the question


#1

It just keeps asking me the question over and over no matter what my answer is–even if it’s “y” or “n”.

choice = raw_input('Enjoying the course? (y/n)')

while choice != "y" or "n":
  choice = raw_input("Sorry, I didn't catch that. Enter again: ")

On top of that, the code seems to just keep running:

I also tried adding an if statement so it has something to do if I give it the correct answer, but it just gives me a weird error.

choice = raw_input('Enjoying the course? (y/n)')
if choice == "y":
  print "Good!"
  elif choice == "n":
    print "Fine."

while choice != "y" or "n":
  choice = raw_input("Sorry, I didn't catch that. Enter again: ")


#2

here:

while choice != "y" or "n":

what are you comparing with n? At the moment nothing, so python will simple validate if the string is true, which it is:

if "n":
    print True

in the second code, you have indent issue.


#3
choice = raw_input('Enjoying the course? (y/n)')

while choice != "y" or "n":
  choice = raw_input("Sorry, I didn't catch that. Enter again: ")

In this case, don’t we perform this check again once the raw input has been entered?

For instance, if the first time it asks ("Enjoying the course? (y/n)), if I answer with something that isn’t a “y” or an “n”, I expect it to prompt me again as indicated in the while loop. ("Sorry, I didn’t catch that. Enter again: ")

But if I answer this time with “y” or “n”, why wouldn’t it make the condition

choice != "y" or "n"

false and break the loop?


#4

Given that the behavior of non-empty string is truthy, just its very existence will yield True in a conditional. We must set it into its own conditional.

if a == b or a == c:

#5

Ahhhhh. I think I get what you mean. Thanks for the quick response!

For clarification (just so I’m actually learning and not just going through the steps here :slight_smile:), what you’re saying is that because these two conditionals get evaluated separately, ie.

choice != "y"

or

"n"

(which is basically evaluated as a single standalone condition)
Technically the second conditional will always resolve to True as you stated, and the loop will never break.

I guess I was parsing things not quite correctly in my mind. :slight_smile:


#6

You design the logic. The computer is dumb and only follows your directions. There is no trick that we can rote learn about programming. We need to make our logic pare down to program logic. We are the ones doing the thinking for the computer, then it goes about emulating it.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.