Simple errors Bug?


#1



Why oring this condition will make this an infinity loop?

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

I knew the answer is using and. but or will be also valid and should not create infinite loop, isn't it?


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

while choice != 'y' or choice!= 'n':  # Fill in the condition (before the colon)
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")


#2

In this instance, or is not the operator to use. We need both conditions to be true, not just one of them. Use and.

OR is short-circuiting, meaning only one operand needs to be true, not both.


#3

Thank you very much.


#4

How can the value of choice be "y" and "n" at the same time? the user is supposed to enter either y or n. therefore, the condition should be (choice!="y" or choice!="n"), isn't it?


#5

I think:

choice!="y" or choice!="n" will create infinite loop because user is gong to enter either y or n or others. therefore,

while(choice!="y" or choice!="n") will always execute because
when user enter y:while (False or True) will give True.(infinite loop)
when user enter n:while (True or False) will give True.(infinite loop)
when user enter others:while (True or True) will give True.(infinite loop)
and the program will crash. So we will use
while(choice!="y" and choice!="n"), This way:
when user enter y: while (False and True) will give False.(exit the loop normally)
when user enter n: while (True and False) will give False.(exit the loop normally)
when user enter others: while (True and True) will give True.(Ask user for input again)


#6

They can't. The expression,

choice != 'y' and choice != 'n'

means neither character has been chosen. The loop will repeat until one of 'y' or 'n' are chosen.

!=  means 'not equal to'.

#7

oh yes. i am sorry. i understand it now. thank you for replying, it helped me. thanks again :slight_smile:


#8

good explanation, its counter-intuitive but given that while executes as long as True, this makes sense.


#9

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