validation - PYTHON: While loops, comparing more than one value -
i can understand how use while loop if compare 1 thing, example:
x=int(input("guess number 1-10")) while x!=7: print("wrong!") x=int(input("try again: ")) print("correct 7. ")
however, if want compare 2 or more values through while loops (especially if want validate something), this:
number=input("would eat 1. cake 2. chocolate 3. sweets: ") while number!= "1" or number != "2" or number != "3": number=input("please input choice [1,2,3]") #some code...
when number
equal 1, 2 or 3, program should proceed... doesn't, no matter value input, program stuck @ infinite loop @ line 2-3. have tried while number != "1" or "2" or "3"
, same infinite loops occurs. when try replacing or
and
, while loop break when number
equals first value compared (which in case "1"
).
is there way can resolve this? :)
if have condition of number != '1' or number != '2'
, 1 of conditions true, it'll never break out of loop. try while number not in ('1', '2', '3')
instead.
Comments
Post a Comment